ruby-on-rails – 渴望使用实例变量加载自定义连接

前端之家收集整理的这篇文章主要介绍了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问题.尝试加载自定义关联会产生:

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.

您可能需要定义两个不同的关联.一个特定于实例,另一个在连接期间使用.

原文链接:https://www.f2er.com/ruby/269727.html

猜你在找的Ruby相关文章