我有以下架构:
我希望可以为两个外键(proposalsauthor_id)调用editor_id,也可以为单独的键(例如author_proposalseditor_proposals)调用User.includes(:proposals),并且我需要有延迟或急切加载它们的选项(例如joins或不加载author_proposals)。
更新:

#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, class_name: 'Proposal', foreign_key: :editor_id
end

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

但我需要一个通用的,它会给我所有的建议(包括editor_proposalshas_many),它也会迫不及待地加载它们。我应该在上使用条件吗?

最佳答案

你可以这样做:

class User < ActiveRecord::Base
  has_many :authored_proposals, class_name: 'Proposal', foreign_key: :author_id
  has_many :editored_proposals, class_name: 'Proposal', foreign_key: :editor_id

  def proposals
    authored_proposals | editored_proposals
  end
end

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

  def users
    author | editor
  end
end

您可以通过执行:proposals来紧急加载User.includes(:authored_proposals, :editored_proposals)。这不是纯铁轨的方式,但似乎更干净的我。
您还可以执行以下操作:
class User < ActiveRecord::Base
  has_many :authored_proposals, class_name: 'Proposal', foreign_key: :author_id
  has_many :editored_proposals, class_name: 'Proposal', foreign_key: :editor_id

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

关于ruby-on-rails - 定义两个外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29560528/

10-11 17:53