我想要一种优雅的方式在 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
你不需要成为专家,这甚至不会解析。这只是传达我的想法的一个例子。
为了清楚起见,我不想要验证(我非常了解它们)。我可以通过多种方式实现这一点,但对于像这样的一般和常见问题来说,它们太老套和复杂了。
我想要的是一种在模型本身中强制执行此功能的方法,而不管它与其他模型的关系如何。
提前感谢您的时间和努力。