【发布时间】:2013-12-04 15:37:25
【问题描述】:
在 Rails 4 中,我有一个典型的 HABTM 设置;
class Author < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :authors
end
我想验证 Post.title 的唯一性,但仅限于每个 Author 的基础上。所以;
- 作者 #1 可以拥有 Post.title 'My Post'
- 作者 #2 可以拥有 Post.title 'My Post'
- 但是,作者 #1 无法创建标题为“我的帖子”的第二个帖子
Post 允许拥有多个 Author,因此我不能只拥有 belongs_to 并使用 validates_uniqueness_of :title, scope: :author_id,而且我不确定如何最好地使用 HABTM。
这可以通过validates 实现吗?还是我需要callback 在保存之前先检查关联的Author 是否有匹配的Post.title?
编辑
我使用以下迁移来设置连接表;
class CreateAuthorsPosts < ActiveRecord::Migration
def change
create_table :authors_posts, id: false, force: true do |t|
t.belongs_to :author, index: true
t.belongs_to :post, index: true
end
add_index :authors_posts, [:author_id, :post_id], unique: true
end
end
【问题讨论】:
标签: ruby-on-rails associations unique has-and-belongs-to-many