While not always the "best" approach, Rails offers what's called a Polymorphic belongs_to association. It prevents you from defining a foreign key in the database because the xxx_id column is referencing an id in one of many possible tables while another column designates the name of that table's model, but it makes the relationship more explicit in Rails. Also, it restricts the model to only belong to one of the other models, as opposed to belonging to one or more, as it would happen using the setup of multiple foreign keys without some additional db magic.
发布评论
评论(2)
虽然Rails 并不总是“最佳”方法,但它提供了所谓的多态belongs_to 关联。它阻止您在数据库中定义外键,因为 xxx_id 列引用许多可能的表之一中的 id,而另一列指定该表模型的名称,但它使 Rails 中的关系更加明确。此外,它限制模型仅属于其他模型之一,而不是属于一个或多个模型,因为使用多个外键的设置会发生这种情况,而无需一些额外的数据库魔法。
While not always the "best" approach, Rails offers what's called a Polymorphic belongs_to association. It prevents you from defining a foreign key in the database because the xxx_id column is referencing an id in one of many possible tables while another column designates the name of that table's model, but it makes the relationship more explicit in Rails. Also, it restricts the model to only belong to one of the other models, as opposed to belonging to one or more, as it would happen using the setup of multiple foreign keys without some additional db magic.
是的,这是正确的方法。
Yes that is the correct approach.