使用AS加入:使用ActiveRecord选择

时间:2021-07-19 22:52:08

I am trying to do this

我想这样做

Version.find(:all, :joins=>"JOIN editions ON versions.edition_id=editions.id JOIN products ON editions.product_id=products.id", :select=>"products.name, versions.name AS what")

but ActiveRecord is not respecting the AS keyword... any ideas?

但ActiveRecord不尊重AS关键字......任何想法?

Edit: Since both fields are called "name" they are colliding, so I only get the last one in the list.

编辑:因为这两个字段都被称为“名称”,所以它们是冲突的,所以我只得到列表中的最后一个。

1 个解决方案

#1


From the query:

来自查询:

Product has_many editions (just specifying the relationship here)

产品has_many版本(仅指定此处的关系)

Edition has_many versions

版本has_many版本

foo = Version.find(:all, :joins=>"JOIN editions ON versions.edition_id=editions.id JOIN products ON editions.product_id=products.id", :select=>"products.name, versions.name AS what")
puts foo.inspect 

This should give you a value:

这应该给你一个价值:

[#<Version name: "foobar1">, #<Version name: "foobar2">]

[# <版本名称:“foobar1”> ,# <版本名称:“foobar2”> ]

foo[0].what # Will print the value of 'what' returned by the query

When I wrote a similar query a similar hierarchy it gave me perfect results. Would you like to share the stack trace if you are getting an error?

当我写一个类似的查询类似的层次结构时,它给了我完美的结果。如果您收到错误,是否要共享堆栈跟踪?

EDIT: foo[0].attributes will print {"name" => "foobar1", "what" => ""} Sorry for the typo here. I had meant to say attributes.

编辑:foo [0] .attributes将打印{“name”=>“foobar1”,“what”=>“”}抱歉这里的拼写错误。我原本打算说出属性。

#1


From the query:

来自查询:

Product has_many editions (just specifying the relationship here)

产品has_many版本(仅指定此处的关系)

Edition has_many versions

版本has_many版本

foo = Version.find(:all, :joins=>"JOIN editions ON versions.edition_id=editions.id JOIN products ON editions.product_id=products.id", :select=>"products.name, versions.name AS what")
puts foo.inspect 

This should give you a value:

这应该给你一个价值:

[#<Version name: "foobar1">, #<Version name: "foobar2">]

[# <版本名称:“foobar1”> ,# <版本名称:“foobar2”> ]

foo[0].what # Will print the value of 'what' returned by the query

When I wrote a similar query a similar hierarchy it gave me perfect results. Would you like to share the stack trace if you are getting an error?

当我写一个类似的查询类似的层次结构时,它给了我完美的结果。如果您收到错误,是否要共享堆栈跟踪?

EDIT: foo[0].attributes will print {"name" => "foobar1", "what" => ""} Sorry for the typo here. I had meant to say attributes.

编辑:foo [0] .attributes将打印{“name”=>“foobar1”,“what”=>“”}抱歉这里的拼写错误。我原本打算说出属性。