gpt4 book ai didi

ruby-on-rails - 两个外键的作用域

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:27 27 4
gpt4 key购买 nike

我有以下架构: enter image description here

我希望可以选择为外键(author_ideditor_id)以及单独的外键(例如 author_proposalseditor_proposals),我需要有延迟或急切加载它们的选项(例如 User.includes(:proposals) 或没有它用连接)。

更新:

#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 :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

关于ruby-on-rails - 两个外键的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29560528/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com