简体   繁体   中英

ruby-on-rails: update_attributes overrides model validations?

I have a typical, Post model:

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.

1) Why?

2) Suggestions on a fix?

Thanks

From the entry on update_attribute in the doc for ActiveRecord::Persistence :

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM