Updating Model Attributes
Asked Answered
L

2

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?

Lateshalatest answered 16/5, 2011 at 11:32 Comment(0)
H
8

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.

Harassed answered 16/5, 2011 at 11:57 Comment(4)
Thanks Beerlington! Is there a way to implement any of these options through the view, perhaps through a button or clickable link?Lateshalatest
This could couldn't be in the view and would have to be in either your controller or model.Harassed
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?Lateshalatest
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.Harassed
T
1

use this

User.find_by_id(user_id).update_attribute(:writer, true) or 
User.find_by_id(user_id).update_attribute(:writer, false)
Terrilyn answered 16/5, 2011 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.