Updating Model Attributes

I have a Rails application, which is a blogging platform that allows multiple authors to use it. My User Model has an attribute : writer for defining write permissions. However : writer is NOT specified in attr_accessible for the User model.

I wanted to edit this attribute over the Internet, without having to run

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

through the console, but I wonder if this is impossible without listing : writer in attr_accessible for the User model. I have several pages available only to admin users, and I would like to be able to switch the : writer attribute into these views.

If this is really possible, how can this be done? Thanks in advance for your help!

Edit: Based on the two answers I received, I believe that should have been more specific in my question. I apologize. I understand that I could individually update the : writer attribute, as Beerlington and Hitesh pointed out. I wanted to know how to implement such a function through a view. Can I make an interactive link to switch state: writer? Is it possible for the link to call the controller function and pass the corresponding user_id to switch : writer ?

+6
source share
2 answers

attr_accessible and attr_protected protect only mass-assignment attributes. You can still assign them in other ways:

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 don't like any of these leadership options, so I wrote a gem called sudo_attributes , which makes it easy to override mass assignments using the sudo methods.

+7
source

use this

 User.find_by_id(user_id).update_attribute(:writer, true) or User.find_by_id(user_id).update_attribute(:writer, false) 
+1
source

Source: https://habr.com/ru/post/888207/


All Articles