我有user
模型,has_one
与user_profile
关联
我想从user_profile中选择name字段,而不是user_profile
。*
我试过了,
user = User.first
user.user_profile.select(:name)
但这不起作用。怎么办?
更新:
看起来,rails处理另一个方向和一对一连接的方式不同。你有两个选择:
1) 定义关联中所选的属性,它将始终选择那些
has_one :user_profile, :select => [:name, :id]
2) 在您的模型中定义一个特定的查找,您可以在其中添加select
,如下所示:
def my_profile
UserProfile.find(self.user_profile_id)
end
....
my_profile.select(:name)
原件:
在has_many
方向的情况下,它起作用:
我在我的代码中尝试过你的方法,比如:
= User.find("admin").article.select(:title).to_sql
它返回正确的sql:
SELECT title
FROM "articles"
WHERE "articles"."user_id" = 1364