Rails 2 :join 和 :include 结果集
当使用 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
这在 AR 中为
Users.find(:all,
:joins => :cities,
:select => "users.name, users.username, users.age, users.city_id,
cities.name as city_name")
但这仅返回用户表结果,而不返回城市结果。我 100% 确定内部联接语句正在执行(两个表都正在联接)。
似乎返回对象仅具有与模型关联的列。因此,UserModel 将仅具有用户表具有的列,并且不允许获取城市表的列,即使它们是在选择中指定的。
我应该使用 :joins 还是 :include?知道发生了什么事吗?
When fetching content from a database using activerecord, I would like to fetch a custom resultset with specified columns across two tables.
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
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).
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.
Should I be using :joins or :include? Any idea what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您为连接的列名称添加别名,则返回的对象应该具有别名的属性,即
在您的情况下,
:joins
比:include
更合适。我在我的设置中检查了这一点,它对我有用(我在 Rails 2.3.8 上)
If you alias the joined column name then returned object should have an attribute by the alias name, i.e.
In your case,
:joins
is appropriate than:include
.I checked this in my setup and it works for me ( I am on Rails 2.3.8)
在返回的实例中,如果列的名称是 city_name,则您应该使用 user.city_name。或者,如果您使用 :include,您将告诉 ActiveRecord 加载关联的城市模型,然后将其引用为 user.city.name。
总结一下:
In your returned instances, if the column's name is city_name, you should be using 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.
To summarize:
如果不需要所有列,可以使用用户表中的特定列名称代替“users.*”。我认为这是很好的编程实践。
u = User.first( :joins => :城市,
:选择=> "users.name, users.username, users.age, users.city_id, cars.name AS city_name")
u.city_name # 返回城市名称。
you can use specific column name in user table in place of "users.*" if you dont need all column. 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.city_name # returns the city_name.