Questions tagged «model-associations»

6
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返回用户1和Task.first.assignee返回用户2但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 这完全失败了,因为似乎不支持两个外键。 …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.