在连接表中,Rails缺少复合键的最好的解决方法是什么? [英] In a join table, what's the best workaround for Rails' absence of a composite key?
问题描述
create_table :categories_posts, :id => false do |t|
t.column :category_id, :integer, :null => false
t.column :post_id, :integer, :null => false
end
我有一个连接表相应的类别表和帖子表。我想对 categories_posts 连接表中的组合键category_id,post_id 强制执行唯一约束。但Rails不支持这个(我相信)。
I have a join table (as above) with columns that refer to a corresponding categories table and a posts table. I wanted to enforce a unique constraint on the composite key category_id, post_id in the categories_posts join table. But Rails does not support this (I believe).
为避免我的数据中的重复行具有category_id和post_id的相同组合,在Rails中缺少组合键的最佳解决方法是什么?
To avoid the potential for duplicate rows in my data having the same combination of category_id and post_id, what's the best workaround for the absence of a composite key in Rails?
我的假设如下:
- 默认自动编号列$ b
- ActiveScaffold可能提供一个
的解决方案,但是我不确定$ $ b(id:integer) b $ b在
项目中包含它只是对于这个单一的
功能,特别是如果有一个
更优雅的答案,它是overkill。
推荐答案
添加一个包含两个列的唯一索引。这将阻止您插入包含重复的category_id / post_id对的记录。
Add a unique index that includes both columns. That will prevent you from inserting a record that contains a duplicate category_id/post_id pair.
add_index :categories_posts, [ :category_id, :post_id ], :unique => true, :name => 'by_category_and_post'
这篇关于在连接表中,Rails缺少复合键的最好的解决方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!