Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - check that object is valid with params before update

I have very newbie question. How can i check that object of model is valid with new params BEFORE updating it?

I want transform that:

def update
  @obj = SomeModel.find( params[:id] )

  if @obj.update_attributes( params[:obj] )
    # That have been updated
  else
    # Ups, errors!
  end
end

To something like that:

def update
  @obj = SomeModel.find( params[:id] )

  if @obj.valid_with_new_params( params[:obj] )
    @obj.update_attributes( params[:obj] )
  else
    # Ups, errors!
  end
end
like image 772
ExiRe Avatar asked May 23 '12 20:05

ExiRe


2 Answers

To update the attributes without saving them, you can use

@obj.assign_attributes( params[:obj] )

Then to check if the object is valid, you can call

@obj.valid?

If the object is not valid, you can see the errors (only after calling .valid?) by calling

@obj.errors

If the object is valid, you can save it by calling

@obj.save

However, all of this usually isn't necessary. If the object isn't valid, then ActiveRecord won't save the object to the database, so all of the attribute changes are forgotten when you leave the controller action.

Also, since an invalid record won't be saved to the database, you can always just call Object.find() again to get the original object back.

like image 181
Justin Avatar answered Nov 16 '22 03:11

Justin


You can call the valid? method to run the validations.

This doesn't guarantee that a subsequent save will succeed if some of your validations depend on the state of other objects in the database. Te save could also fail for reasons unconnected to validations (eg a foreign key constraint)

I'm not sure why you'd want this pattern

like image 27
Frederick Cheung Avatar answered Nov 16 '22 02:11

Frederick Cheung