如何使模型在rails 4中不包含重复项

时间:2013-11-14 02:56:54

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

我想要一种优雅的方法让它在rails 4中工作:

# this is a neted_attribute for the model User
class Category < ActiveRecord::Base
  belongs_to :user
  attr_accessible name, code

  # to make sure that when the user try to create a Category where exists
  # a category that has the same attributes it assigns
  # the current category to the existing one
  before_save do
    self = Category.where(name: name, code: code).first_or_initialize
  end
end

你不需要成为专家,甚至不会解析。它只是 传达我的想法的一个例子。

要明确我不想要验证(我非常了解它们)。 我可以通过多种方式实现这一目标,但他们会这样做 对于像这样的一般和常见问题来说太过于苛刻和复杂。

我想要的是一种在模型中强制执行此功能的方法 它与其他模型的关系。

提前感谢您的时间和精力。

2 个答案:

答案 0 :(得分:0)

你不能这样做。正如您可能已经注意到的,Ruby不允许您分配给self,因为这个概念毫无意义。在before_save过滤器中,您可以更改id以匹配现有记录,但save会失败,因为ActiveRecord会尝试在数据库中插入新记录与现有记录相同id,导致数据库唯一性违规。

答案 1 :(得分:0)

关注:

module CreateCategory
  def find_or_create_category(name, code)
    cat = Category.where(name: name, code: code).first_or_create
    self.categories << cat
    cat
  end
end

在user.rb中:

include CreateCategory

创建类别时,请使用@category = user.find_or_create_category(name, code)