Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Model Attributes

I have a Rails app that is a blogging platform, allowing for multiple contributing authors. My User model has a :writer boolean attribute for assigning writing permissions. However, :writer is NOT listed under attr_accessible for the User model.

I wanted to a way to edit this attribute through the web, without having to run

User.find_by_id(user_id).update_attribute(:writer, true/false)

through the console, but I'm wondering if this would be impossible without listing :writer under attr_accessible for the User model. I have several pages accessible only to admin-users, and I would like to be able to put the ability to toggle the :writer attribute within those views.

If it is indeed possible, how could it be done? Thanks in advance for your help!

Edit: Based on the couple of answers I've gotten, I feel should've been more specific in my question. I apologize. I understand that I could still individually update the :writer attribute, as Beerlington and Hitesh have pointed out. What I wanted to know was how one could implement such a function through the view. Would it be possible to make a clickable link to toggle the :writer state? Might it be possible to have a link call a controller function and pass the appropriate user_id for :writer toggling?

like image 895
ArcGhost Avatar asked May 16 '11 11:05

ArcGhost


1 Answers

attr_accessible and attr_protected only protect attributes from mass-assignment. You can still assign them through other means though:

Mass Assignment (will not work):

model.update_attributes(:admin => true)

Non Mass Assignment (option 1):

model.admin = boolean
model.save

Non Mass Assignment (option 2):

model.send(:attributes=, attributes, false)

Non Mass Assignment (option 3):

model.update_attribute(admin, boolean)

I personally do not like either of these manual options, so I wrote a gem called sudo_attributes that makes it easier to override mass assignment using "sudo" methods.

like image 77
Peter Brown Avatar answered Sep 18 '22 00:09

Peter Brown