我也在为这种行为而苦苦挣扎......
代码:
@thing.tag_ids = params[:thing][:tag_ids]
在 DB ad hoc 中进行更改并且它不调用验证,因此:
@thing.update_attributes(params[:thing][:tag_ids])
不同于
@thing.tag_ids = params[:thing][:tag_ids]
@thing.save
简而言之:
@thing.tag_ids = params[:thing][:tag_ids] # makes changes in DB w/o validations
@thing.save # runs validations before making changes to DB
我还问是否有可能在使用时运行验证:
@instance.collection_singular_ids = other_singular_ids
作为快速修复,我向父模型(“事物”)添加了覆盖方法,如下所示:
def tag_ids=(ids)
super
rescue ActiveRecord::RecordInvalid => e
self.errors.add(:base, e.message)
end
和验证器以防止在连接模型中重复标签,如下所示:
validates :tag_id, :uniqueness => {:scope => :thing_id}
有没有人有更好的解决方法?