0

我想要一种优雅的方式在 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

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

为了清楚起见,我不想要验证(我非常了解它们)。我可以通过多种方式实现这一点,但对于像这样的一般和常见问题来说,它们太老套和复杂了。

我想要的是一种在模型本身中强制执行此功能的方法,而不管它与其他模型的关系如何。

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

4

2 回答 2

0

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

于 2013-11-14T03:52:06.030 回答
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)

于 2013-11-14T15:48:50.457 回答