我在has_many上组合多个外键时遇到问题。我知道这不是foreign_key对has_many的明确意图。但无论我是在寻找一种简单的方法来组合两个外键。
我尝试过将两个has_many结合起来:
has_many :primary_clients, foreign_key: :coach_id, inverse_of: :coach do
end
has_many :secondary_clients, foreign_key: :coach_two_id, inverse_of: :coach do
end
def clients
Client.where("primary_clients = ? OR secondary_clients = ?", self.id, self.id)
end
我还试图重新定义范围:
has_many :clients, ->(user) { unscope(:where).where("coach_id = :id OR coach_two_id = :id", id: ids) }, inverse_of: :coach do
end
我喜欢非常简单的事情之后:
has_many :clients, foreign_key: {:coach_id, :coach_two_id}, inverse_of: :coach do
end
有任何反馈意见指向正确的方向吗?
答案 0 :(得分:0)
对于你可以做的非常小的收藏
使用primary_clients | secondary_clients
运算符union
|