gpt4 book ai didi

ruby-on-rails - rails 2 :joins and :include resultset

转载 作者:搜寻专家 更新时间:2023-10-30 20:13:07 25 4
gpt4 key购买 nike

当使用 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?知道发生了什么事吗?

最佳答案

如果您为连接的列名称设置别名,则返回的对象应具有别名的属性,即

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

在您的情况下,:joins:include 更合适。

我在我的设置中检查了这个,它对我有用(我在 Rails 2.3.8 上)

关于ruby-on-rails - rails 2 :joins and :include resultset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com