使用两个外键确定范围

Joh*_*Del 13 ruby activerecord ruby-on-rails rails-activerecord

我有以下架构: 在此输入图像描述

我想要选择同时调用proposalsforeign_keys(author_ideditor_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
Run Code Online (Sandbox Code Playgroud)

但我需要一个通用的一个,它会给我所有的提案(包括author_proposalseditor_proposals),这也将跃跃欲试加载它们.我应该使用条件has_many吗?

spi*_*ann 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
Run Code Online (Sandbox Code Playgroud)


Sau*_*abh 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
Run Code Online (Sandbox Code Playgroud)

你可以贪婪加载proposals做:User.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
Run Code Online (Sandbox Code Playgroud)