开发者

Any problems with multiple foreign key columns in a Rails class?

开发者 https://www.devze.com 2022-12-08 18:48 出处:网络
I\'m coding a site that\'s using tags.Two other classes (Foo and Bar) both will use tags, but the tags used in Foo won\'t apply to Bar, and vice-versa.So I created the Tags table with both foo_id and

I'm coding a site that's using tags. Two other classes (Foo and Bar) both will use tags, but the tags used in Foo won't apply to Bar, and vice-versa. So I created the Tags table with both foo_id and bar_id columns, so when a record is s开发者_开发技巧aved, the foreign key for the correct object-type can be added.

Will this cause problems? Is there a more elegant way to store Tags?


You are implementing a many-to-many relation.

Use a join table with tag_id, foo_id. Then in your model classes use has_and_belongs_to_many or has_many :through.

Use a separate join table for bar.

See http://blog.hasmanythrough.com/2006/04/20/many-to-many-dance-off


You can either have separate join tables as jakber says, or use Single Table Inheritance, storing both foo tags and bar tags in the same table with a type field that specifies whether the id is for a foo or for a bar.

You might also like the acts _ as _ taggable _ on _ steroids plugin, it's very simple and handles tags nicely.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号