ruby-on-rails: update_attributes overrides model validations?

Posted by cbrulak on Stack Overflow See other posts from Stack Overflow or by cbrulak
Published on 2010-03-19T02:58:16Z Indexed on 2010/03/19 3:01 UTC
Read the original article Hit count: 481

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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about model-validations