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