两个外键的作用域

Scoping with two foreign keys

我有以下架构:

我希望可以选择为 foreign_keys(author_ideditor_id)以及单独的调用 proposals(例如 author_proposalseditor_proposals),我需要选择延迟或急切加载它们(例如 User.includes(:proposals) 或不使用 joins)。

更新:

#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

但我需要一个通用的,它会给我所有的建议(author_proposalseditor_proposals),它也会急切地加载它们。我应该在 has_many 上使用条件吗?

像这样设置你的关联:

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

我会这样做:

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
    Proposal.where('author_id = :id OR editor_id = :id', { id: id }).distinct
  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
    User.where(id: [author_id, editor_id].uniq)
  end
end

您可以这样做:

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

您可以通过执行以下操作预先加载 proposalsUser.includes(:authored_proposals, :editored_proposals)。这不是纯粹的 rails 方式,但对我来说似乎更干净。



你也可以这样做:

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