微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐