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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用两个外键设置范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下模式:

我想要选择为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
原文链接:https://www.f2er.com/ruby/271626.html

猜你在找的Ruby相关文章