加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:40:01 所属栏目:百科 来源:网络整理
导读:给定一个允许用户邀请其他用户参加活动的系统: class Event has_many :invitesendclass User has_many :invites has_many :invited,inverse_of: :inviter,foreign_key: :inviter_id,class_name: 'Invite'endclass Invite belongs_to :user belongs_to :even
给定一个允许用户邀请其他用户参加活动的系统:
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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读