通过基于连接表中的字段的字段的唯一性来实现许多

时间:2013-05-02 04:45:15

标签: ruby-on-rails

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  

这是一个has_many通过关系,其中post_categories是连接表。

在Post Model中有一个名为:title的字段。我需要确保帖子中的所有标题对于给定类别都是唯一的。如何根据连接表中的category_id执行验证?

1 个答案:

答案 0 :(得分: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