使用两个外键确定范围

时间:2015-04-10 11:40:10

标签: ruby-on-rails ruby activerecord rails-activerecord

我有以下架构: enter image description here

我希望可以选择为两个foreign_keys(proposalsauthor_id)调用editor_id以及另外一个(例如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上的条件吗?

3 个答案:

答案 0 :(得分:7)

我会做这样的事情:

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

答案 1 :(得分:6)

您可以执行以下操作:

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

答案 2 :(得分:1)

设置您的关联:

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