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

标签 ruby-on-rails ruby

给定一个允许用户邀请其他用户参加事件的系统:

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/

相关文章:

ruby-on-rails - 部署 Rails 应用程序

ruby-on-rails - 如何在 Rails 应用程序中测试简单的 Ruby 类?

ruby-on-rails - 从头开始使用 ajax 创建 Web 应用程序还是稍后添加 ajax?

ruby-on-rails - 在 Ruby 中并行运行命令行进程

ruby - 带条件的 Rails 计数器缓存

ruby - Class.superclass = 模块,Module.class = 类?

ruby - 是否可以通过 Web 应用程序的 Java 对话框提示用户输入密码?

ruby - 在 ruby​​ 中运行手动 GC 是好习惯吗

ruby-on-rails - Minitest IntegrationTest ArgumentError : unknown keyword: session

ruby - 中间人检查页面是否存在