Marius Butuc
Marius Butuc

Reputation: 18250

Rails 3 best practice to modify a boolean attribute?

What is the best practice to switch a boolean attribute e.g., un-/publish an article?

For the Model side, I saw Object.update_attribute(:only_one_field, 'my_value') is best for this job, instead of update_attributes.

What about

  1. the View (use a link, a submit button in a form, other ideas?) and
  2. the Controller side?

Upvotes: 1

Views: 1120

Answers (1)

Brett Bender
Brett Bender

Reputation: 19738

  1. Views usually use forms for updating models. The form_for helper makes this pretty straightforward.

  2. If you are using a standard update action (your controller inherits from InheritedResources::Base) then your update! method in your controller should handle this fine.

I would actually advise against using Model.update_attribute(:published, value) unless you are aware that this call bypasses your model's validations. This is generally why forms just post to the update or create methods in the controller - those by default go through the entire ActiveRecord lifecycle, calling your validations as well. If you have a reason to bypass them, then by all means use update_attribute.

Upvotes: 1

Related Questions