简体   繁体   English

Rails 2:join和:include resultset

[英]Rails 2 :joins and :include resultset

When fetching content from a database using activerecord, I would like to fetch a custom resultset with specified columns across two tables. 使用activerecord从数据库中获取内容时,我想在两个表中获取具有指定列的自定义结果集。

SELECT users.name, users.username, users.age, users.city_id, cities.name as city_name FROM users INNER JOIN cities ON users.city_id = cities.id

Which would be in AR as 哪个会在AR中

Users.find(:all, 
   :joins => :cities, 
   :select => "users.name, users.username, users.age, users.city_id,
      cities.name as city_name")

But this only returns the user table results and not the city results. 但这只返回用户表结果而不是城市结果。 I am 100% sure that the inner join statement is going through (that both tables are being joined). 我100%确定内部连接语句正在通过(两个表都被连接)。

It seems as if the return object only has the columns associated with the model. 似乎返回对象只有与模型关联的列。 So UserModel would only have the columns that the users table has and won't allow to fetch the columns of the cities table even though they're specified in the select. 因此,UserModel只会拥有users表所具有的列,并且不会允许获取cities表的列,即使它们已在select中指定。

Should I be using :joins or :include? 我应该使用:加入还是:包含? Any idea what's going on? 知道发生了什么事吗?

If you alias the joined column name then returned object should have an attribute by the alias name, ie 如果您为已连接的列名添加别名,则返回的对象应具有别名的属性,即

u = User.first( :joins => :cities, 
      :select => "users.*, cities.name AS city_name")
u.city_name # returns the city_name.

In your case, :joins is appropriate than :include . 在您的情况下, :joins:include更合适。

I checked this in my setup and it works for me ( I am on Rails 2.3.8) 我在我的设置中检查了这个并且它适用于我(我在Rails 2.3.8上)

In your returned instances, if the column's name is city_name, you should be using user.city_name. 在返回的实例中,如果列的名称是city_name,则应使用user.city_name。 Alternatively, if you use :include, you would be telling ActiveRecord to load the associated city models, which you would then reference as user.city.name. 或者,如果您使用:include,您将告诉ActiveRecord加载关联的城市模型,然后您将其引用为user.city.name。

To summarize: 总结一下:

users = User.find(:all, :joins => :cities, :select => "users.name, users.username, users.age, users.city_id, cities.name as city_name")
users.map(&:city_name)

users = User.find(:all, :include => :cities)
users.map(&:city).map(&:name)

you can use specific column name in user table in place of "users.*" if you dont need all column. 如果您不需要所有列,则可以在用户表中使用特定列名来代替“users。*”。 I think its good programming practice. 我认为它的编程实践很好。

u = User.first( :joins => :cities, :select => "users.name, users.username, users.age, users.city_id, cities.name AS city_name") u = User.first(:joins =>:cities,:select =>“users.name,users.username,users.age,users.city_id,cities.name AS city_name”)

u.city_name # returns the city_name. u.city_name#返回city_name。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM