0
class Post  
  has_many :post_categories  
  has_many :categories, :through => :post_categories
end

class PostCategory
 belongs_to :post  
 belongs_to :category
end  

class Category
 has_many :post_categories
 has_many :posts, :through => :post_categories
end  

これは、post_categories が結合テーブルである has_many スルー リレーションシップです。

Post Model に :title というフィールドがあります。投稿内のすべてのタイトルが特定のカテゴリで一意であることを確認する必要があります。結合テーブルの category_id に基づいて検証を実行するにはどうすればよいですか?

4

1 に答える 1

0

私はこれがうまくいくはずだと思いますが、試していません。

検証:unique_title

def unique_title
  if self.new_record?
    self.errors.add(:title, "is taken") if self.category.posts.where(:title => self.title).exists?
  else
    self.errors.add(:title, "is taken") if self.category.posts.where("title = '#{self.title}' and id NOT IN (#{self.id})").exists?
  end
end
于 2013-05-02T05:12:44.920 に答える