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

ruby-on-rails – 使用两个外键设置范围

发布时间:2020-12-16 19:40:01 所属栏目:百科 来源:网络整理
导读:我有以下模式: 我想要选择为foreign_keys(author_id和editor_id)以及单独的一个(例如author_proposals和editor_proposals)调用投标,我需要选择懒惰或加载它们(例如User.includes(:提案)或没有连接). 更新: #I have the scopes which is like this:class U
我有以下模式:

我想要选择为foreign_keys(author_id和editor_id)以及单独的一个(例如author_proposals和editor_proposals)调用投标,我需要选择懒惰或加载它们(例如User.includes(:提案)或没有连接).

更新:

#I have the scopes which is like this:
class User < ActiveRecord::Base
  has_many :author_proposals,class_name: 'Proposal',foreign_key: :author_id
  has_many :editor_proposals,foreign_key: :editor_id
end

class Proposal < ActiveRecord::Base
  belongs_to :author,class_name: 'User',foreign_key: :author_id
  belongs_to :editor,foreign_key: :editor_id
end

但我需要一个通用的,它将给我所有的建议(author_proposals和editor_proposals),它也将加载它们.我应该在has_many上使用条件吗?

解决方法

你可以这样做:
class User < ActiveRecord::Base
  has_many :authored_proposals,foreign_key: :author_id
  has_many :editored_proposals,foreign_key: :editor_id

  def proposals
    authored_proposals | editored_proposals
  end
end

class Proposal < ActiveRecord::Base
  belongs_to :author,foreign_key: :editor_id

  def users
    author | editor
  end
end

您可以通过执行以下操作来加载提案:User.includes(:authored_proposals,:editored_proposals).这不是纯粹的铁路方式,但对我来说似乎更清洁.

你也可以做:

class User < ActiveRecord::Base
  has_many :authored_proposals,foreign_key: :editor_id

  has_many : proposals,finder_sql: proc { "SELECT * FROM proposals WHERE (proposals.author_id = #{id} or proposals. editor_id = #{id})" }
end

(编辑:李大同)

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

    推荐文章
      热点阅读