ruby-on-rails – 渴望使用实例变量加载自定义连接
给定一个允许用户邀请其他用户参加活动的系统:
class Event has_many :invites end class User has_many :invites has_many :invited,inverse_of: :inviter,foreign_key: :inviter_id,class_name: 'Invite' end class Invite belongs_to :user belongs_to :event belongs_to :inviter,class_name: 'User' has_many :invited,-> (invite) { where(invites: { event_id: invite.event_id }) },through: :user,class_name: 'Invite' end 我正在生成一个简单的报告,显示事件的所有邀请.我正在尝试修改报告,以包含一些可以针对示例事件的邀请执行的操作: <%- event.includes(:user).each do |invite| -%> <%= invite.user.name %> <%- invite.invited.each do |other| -%> <%= link_to invite_path(other),method: :destroy do %> ... <% end %> <%- end -%> <%- end -%> 这工作正常,但有一个N 1问题.尝试加载自定义关联会产生:
有没有办法做这样的急切加载?是否可以给has_many提供其他提示而不是使用实例变量? 解决方法
见
Rails 5 how to form association between tables on multiple shared attributes.
您可能需要定义两个不同的关联.一个特定于实例,另一个在连接期间使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |