gpt4 book ai didi

ruby-on-rails - 如何访问 has_many :through association object's relevant join model without additional queries?

转载 作者:行者123 更新时间:2023-12-03 15:51:04 25 4
gpt4 key购买 nike

这是我现在遇到过很多次的事情,我很想弄清楚如何做我想做的事情,或者构建并向 Rails 提交一个补丁来完成它。很多时候在我的应用程序中,我会有一些看起来像这样的模型:

class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
end

class Membership
belongs_to :user
belongs_to :group

def foo
# something that I want to know
end
end

class Group
has_many :memberships
has_many :users, through: :memberships
end

我希望能够做的是通过调用关联访问相关成员资格,而无需进行其他查询。例如,我 想要做这样的事情:
@group = Group.first
@group.users.each do |user|
membership = user.membership # this would be the membership for user in @group
end

Rails 中有什么允许这样做的吗?因为我知道要达到我所说的结果的唯一方法是非常丑陋和低效的,就像这样:
@group.users.each do |user|
membership = Membership.where(group_id: @group.id, user_id:user.id).first
end

ActiveRecord 是否有一些神秘的内置工具来实现这一点?看起来它不会太难,它已经必须获取连接模型才能正确检索关联,因此如果此功能不存在,在我看来它应该存在。我已经遇到过很多次了,我已经准备好卷起袖子彻底解决它了。我能做什么?

更新:我可以使用的另一种模式基本上得到了我想要的东西是这样的:
@group.memberships.includes(:user).each do |membership|
user = membership.user
end

但从美学上讲,我不喜欢这个解决方案,因为我实际上对成员资格并不感兴趣,因为我是用户,并且迭代连接模型而不是关联目标感觉是错误的。但这比我上面指出的另一种方式要好(感谢 Intridea 的 Ian Yang 提醒我这一点)。

最佳答案

如果你只是想访问成员(member)中的一些属性,有一个丑陋的技巧

group.users.select('*, memberships.some_attr as membership_some_attr')

它有效是因为成员资格隐式包含在 JOIN 中。

更新

更重要的是,如果你在 User 中添加另一个丑陋的技巧

class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
belongs_to :membership #trick, cheat that we have membership_id
end

现在:

group.users.select('*, memeberships.id as membership_id').includes(:membership).each do |user|
membership = user.membership
end

关于ruby-on-rails - 如何访问 has_many :through association object's relevant join model without additional queries?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6365215/

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