[英]ruby-on-rails: update_attributes overrides model validations?
I have a typical, Post model: 我有一个典型的Post模型:
class Post< ActiveRecord::Base
validates_presence_of :user_id #Line 1
validates_presence_of :title,:body #Line 2
in the controller, I have: 在控制器中,我有:
def create
if request.post?
if login_required
@post = Post.new(params[:post]) #Line 3
@post .update_attribute("user_id",session[:userid]) #Line 4
However, if the validations on Line 2 fail the Post will still be created, unless Line 4 is commented out. 但是,如果第2行的验证失败,则除非注释第4行,否则仍将创建该帖子。
1) Why? 1)为什么?
2) Suggestions on a fix? 2)关于修复的建议?
Thanks 谢谢
From the entry on update_attribute
in the doc for ActiveRecord::Persistence : 从ActiveRecord :: Persistence的文档中
update_attribute
上的条目中:
Updates a single attribute and saves the record without going through the normal validation procedure.
更新单个属性并保存记录,而无需执行正常的验证过程。 This is especially useful for boolean flags on existing records.
这对于现有记录上的布尔标志特别有用。
Seems like it's a loophole to help you avoid the overhead of validation when you make a quickie tweak to a record. 似乎是一个漏洞,可以帮助您避免在对记录进行快速调整时避免验证的开销。 If you want validation, just use
如果要验证,只需使用
@post.update_attributes(:user_id => session[:userid])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.