简体   繁体   English

如何制作模型在Rails 4中不包含重复项

[英]how to make a model doesn't contain duplicates in rails 4

I want an elegant way to make this work in rails 4: 我想要一种优雅的方法来使它在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

You don't need to be an expert to that this won't even parse. 您不需要成为专家,甚至都不会解析。 It is merely an example to convey my idea. 这只是传达我的想法的一个例子。

Just to be clear I don't want validations (I'm very well aware of them). 为了清楚起见,我不需要验证(我对验证非常了解)。 And I can achieve this in many ways, but they would be too hacky and complex for a general and common problem like this. 而且我可以通过多种方式实现这一目标,但是对于像这样的一般性和常见问题,它们将过于笨拙和复杂。

What I want is a way to enforce this feature in the model itself regardless of its relation with other models. 我想要的是一种在模型本身中强制执行此功能的方法,无论其与其他模型的关系如何。

Thanks in advance for your time and efforts. 在此先感谢您的时间和精力。

You cannot do this. 你不可以做这个。 As you probably noted, Ruby does not allow you to assign to self , as the concept makes no sense. 您可能已经注意到,Ruby不允许您将其分配给self ,因为该概念没有意义。 In the before_save filter, you could change id to match the existing record, but the save would fail because ActiveRecord would try to insert a new record in the database with the same id as an existing record, resulting in a database uniqueness violation. before_save过滤器中,您可以更改id以匹配现有记录,但是save会失败,因为ActiveRecord会尝试在数据库中插入一个与现有记录具有相同id的新记录,从而导致数据库唯一性冲突。

In a concern: 在关注中:

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

In user.rb: 在user.rb中:

include CreateCategory

When you create the category, use @category = user.find_or_create_category(name, code) 创建类别时,请使用@category = user.find_or_create_category(name, code)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM