6

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?

ArcGhost
  • 137
  • 1
  • 2
  • 11

2 Answers2

7

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.

Peter Brown
  • 48,818
  • 16
  • 106
  • 142
  • Thanks Beerlington! Is there a way to implement any of these options through the view, perhaps through a button or clickable link? – ArcGhost May 16 '11 at 13:29
  • This could couldn't be in the view and would have to be in either your controller or model. – Peter Brown May 16 '11 at 21:59
  • If I were to create a method to do this called, say, toggle_writer, in my controller, could _that_ be called through a button or clickable link? – ArcGhost May 16 '11 at 22:59
  • Yea you could definitely do that. There are a dozen ways you could do it though. If you're still unsure, I'd recommend creating another question and someone could give you help. – Peter Brown May 17 '11 at 01:03
1

use this

User.find_by_id(user_id).update_attribute(:writer, true) or 
User.find_by_id(user_id).update_attribute(:writer, false)
Hitesh
  • 815
  • 1
  • 6
  • 11