Ruby on rails Rails接受\u嵌套的\u属性\u进行验证
一个Ruby on rails Rails接受\u嵌套的\u属性\u进行验证,ruby-on-rails,validation,activerecord,Ruby On Rails,Validation,Activerecord,一个图像有许多类别。 它也是一个accepts\u nested\u attributes\u for:categories。 类别只有id和说明。我希望它在创建之前验证类别,而不是创建具有相同描述的重复类别,这样,如果用户输入的类别已经存在,它只会将类别设置为已经存在的类别 我已经尝试向图像类和类别类添加钩子,但这两种方法似乎都没有改变类别,以使其通过验证 以下是我尝试过的(在图像类和类别类上都添加了此选项): 可能不是最好的解决方案,但它应该让您开始 # Get the value of t
图像有许多类别。
它也是一个accepts\u nested\u attributes\u for:categories
。
类别
只有id
和说明
。我希望它在创建之前验证类别,而不是创建具有相同描述的重复类别,这样,如果用户输入的类别已经存在,它只会将类别设置为已经存在的类别
我已经尝试向图像类
和类别类
添加钩子,但这两种方法似乎都没有改变类别
,以使其通过验证
以下是我尝试过的(在图像类
和类别类
上都添加了此选项):
可能不是最好的解决方案,但它应该让您开始
# Get the value of the category_description from the form
@category_description = params[:image][:category_attributes][:description]
# check if it already exists
if Category.exists?(description: @category_description)
# if it exists then find the category and pass it to the image
@existing_category = Category.where(description: @category_description).first
@image = Image.new(image_params.merge({ category: @existing_category }))
else
# if not, create a new image and category
@image = Image.new(image_params)
end
有几种方法可以找到一个现有的类别,但这应该让你去 可以在关联上使用钩子,a la:
has_many :categories, after_add: :chk_category
这将导致每次将类别添加到图像时调用chk_category方法,因此,您可以执行以下操作:
def chk_user(category)
exist_category = Category.where(title: category.title).first
if exist_category
self.categories = self.categories + [exist_category]
self.categories = self.categories - [category]
end
end
您需要在这里编写一些测试,以确保避免递归等,但我认为挂钩应该会有所帮助。谢谢!这是可行的,但我想知道是否有一种方法可以通过hook
将validation
直接添加到Category类
,从而允许它引用自身或创建一个新实例(如果它已经存在)。Category类
负责验证自身,而不是Image类
。如果在Category类上设置了验证,则在本解决方案中会得到尊重。因此,只需在Category类中使用普通验证。也就是说,如果您正在使用它,并且通过code
(Image.categories\u属性)传入的类别表示一个新类别,它将被创建,并将在过程中被验证。在创建之前还有和其他可以添加到类别中的挂钩。这些可能是为了适应你的情况。
def chk_user(category)
exist_category = Category.where(title: category.title).first
if exist_category
self.categories = self.categories + [exist_category]
self.categories = self.categories - [category]
end
end