给定一个允许用户邀请其他用户参加事件的系统:
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
我正在生成一个简单的报告,显示一个事件的所有邀请。我正在尝试修改报告以包含一些可以针对示例事件的 invited
执行的操作:
<%- 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 问题。尝试预先加载自定义关联会给出:
DEPRECATION WARNING: The association scope 'invited' is instance dependent (the scope block takes an argument). Preloading happens before the individual instances are created. This means that there is no instance being passed to the association scope. This will most likely result in broken or incorrect behavior. Joining, Preloading and eager loading of these associations is deprecated and will be removed in the future.
有没有办法像这样进行预加载?是否可以为 has_many
提供其他提示而不是使用实例变量?
最佳答案
参见 Rails 5 how to form association between tables on multiple shared attributes .
您可能需要定义两个不同的关联。一个特定于实例,另一个在连接期间使用。
关于ruby-on-rails - 渴望使用实例变量加载自定义连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605120/