我希望能够在一个表上使用两列来定义关系。因此以任务应用程序为例。具有多个外键的Rails关联
尝试1:
class User < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :owner, class_name: "User", foreign_key: "owner_id"
belongs_to :assignee, class_name: "User", foreign_key: "assignee_id"
end
所以后来Task.create(owner_id:1, assignee_id: 2)
这让我执行Task.first.owner
返回用户一个和Task.first.assignee
返回用户进行的两次但User.first.task
回报什么。这是因为任务不属于用户,他们属于所有者和受让人。所以,
尝试2:
class User < ActiveRecord::Base
has_many :tasks, foreign_key: [:owner_id, :assignee_id]
end
class Task < ActiveRecord::Base
belongs_to :user
end
这只是完全失败的两个外键似乎并没有得到支持。
所以我想要能够说User.tasks
并获得用户拥有和分配的任务。
基本上莫名其妙构建应等于Task.where(owner_id || assignee_id == 1)
查询中的关系是可能的吗?
更新
我不希望使用finder_sql
,但这个问题的接受的答案看起来是接近我想要的:Rails - Multiple Index Key Association
那么这种方法应该是这样的,
尝试3:
class Task < ActiveRecord::Base
def self.by_person(person)
where("assignee_id => :person_id OR owner_id => :person_id", :person_id => person.id
end
end
class Person < ActiveRecord::Base
def tasks
Task.by_person(self)
end
end
虽然我可以得到它在012工作,我不断收到以下错误:
ActiveRecord::PreparedStatementInvalid: missing value for :owner_id in :donor_id => :person_id OR assignee_id => :person_id
这是宝石你在找什么? https://github.com/composite-primary-keys/composite_primary_keys – mus
感谢信息mus,但这不是我要找的。我想要一个查询或列是一个给定的值。不是复合主键。 – JonathanSimmons
是的,更新说明清楚。忘记宝石。我们都认为你只是想使用组合的主键。这至少应该可以通过定义一个自定义作用域的范围关系来实现。有趣的场景。我将在稍后看一看 –