开发者

Updating Model Attributes

开发者 https://www.devze.com 2023-03-06 17:09 出处:网络
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, 开发者_运维百科:writ

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?


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.


use this

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号