为什么
@thing.tag_ids = params[:thing][:tag_ids]
将关系立即保存到数据库中,但是
@thing.update_attributes(params[:thing][:tag_ids])
如果验证失败了就不会了吗?
@thing.update_attributes(params[:thing][:tag_ids])
等同于
@thing.tag_ids = params[:thing][:tag_ids]
@thing.save
难到不是么?
发布于 2013-11-05 01:14:54
你是对的,以下两个陈述是完全相同的:
# save
@thing.key = value
@thing.save
# update
@thing.update_attributes({key: value})
你的代码的问题是你有一个语法问题,你想:
@thing.update_attributes({tag_ids: params[:thing][:tag_ids]})
发布于 2013-11-05 01:41:41
这里的解决方案是,第一种方法似乎是使用update_attribute来更新单个属性,因此从不执行验证。但是在我们所知的update_attributes的情况下,总是执行验证
点击此处阅读更多信息:- http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute
发布于 2015-04-29 18:16:31
我也在为这种行为而苦苦挣扎。
代码:
@thing.tag_ids = params[:thing][:tag_ids]
在数据库中进行即席更改,并且不调用验证,因此:
@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}
有谁有更好的解决方法吗?
https://stackoverflow.com/questions/19772534
复制相似问题