I am creating a Rails application that is a blogging platform, with many contributing writers. My User model has a :writer boolean attribute to indicate whether or not a particular user has permission to publish an article. In order to prevent mass assignment, the :writer attribute is NOT listed under attr_accessible for the User model. Instead, I thought of creating a function similar to the following, to allow for toggling of the writer-permissions:
def toggle_writer
if User.find(:id).writer?
User.find(:id).update_attribute(:writer, false)
else
User.find(:id).update_attribute(:writer, true)
end
flash[:success] = "User permissions toggled."
redirect_to admintools_users_path
end
I have several questions regarding this approach, though:
- How would I invoke this from a view? Is there a way to invoke a function via a link_to or button_for?
- Where would I put such a function? In a controller, or helper?
- Would I need to edit any routes in the config/routes.rb file?
Thanks in advance for your help!
users_controller.Yes, you would. As this action is going to update a single user, so, you should do the following in
routes.rb:Now you can use this route with
link_to, likelink_to("Toggle writer", toggle_writer_for_user_path(@user)), where@useris you can get fromparams[:id].