活动记录查询返回 user_ids 的哈希值,查找每个用户的属性
用户有很多关系
在我的关系表中,我有一个字段:referee,其中包含每个记录的 user_id 。 每条记录还有 user_id 外键
我想查找 :referee 字段中具有 current_user.id 的记录,并从每条记录的外键字段中选择 user_id 。
refs = Relationship.where(:referee => current_user.id).select("user_id").all
这会产生一个像这样的数组,
[#<Relationship user_id: 16>, #<Relationship user_id: 17>]
我现在想要找到数组中每个 id 的用户属性,我已经尝试过,但到目前为止失败了,例如:
User.where(:id => @refs_user_id).each do |user|
user.name
end
对活动记录高级查询、范围等进行了一些读取/观看,但是似乎不太明白这里需要什么。任何建议将不胜感激,谢谢!
User has many Relationships
In my relationships table i have a field :referee containing a user_id for each record.
Each record also has user_id foreign key
I want to find the records that have current_user.id in the :referee field and select user_id from the foreign key field for each one.
refs = Relationship.where(:referee => current_user.id).select("user_id").all
This results in an array like this,
[#<Relationship user_id: 16>, #<Relationship user_id: 17>]
I now want to find User attributes for each of the ids in the array, I've tried but so far failed, for example:
User.where(:id => @refs_user_id).each do |user|
user.name
end
Did some reading/watching on active record advanced queries, scopes etc but can't quite seem to grasp what's required here. Any suggestions would be much appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 ids 数组传递给 ActiveRecord
如果您只想获取 ids:
那只会返回 ids。
You can just pass an array of ids to
ActiveRecord
And if you just want to get the ids:
That will only return the ids.
您可以仅选择
user_id
组件,如下所示:You can select just the
user_id
components like this: