0

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:

  1. How would I invoke this from a view? Is there a way to invoke a function via a link_to or button_for?
  2. Where would I put such a function? In a controller, or helper?
  3. Would I need to edit any routes in the config/routes.rb file?

Thanks in advance for your help!

ArcGhost
  • 137
  • 1
  • 3
  • 12

1 Answers1

2
  1. Yes you can.
  2. Better if you put it in the users_controller.
  3. Yes, you would. As this action is going to update a single user, so, you should do the following in routes.rb:

     resources :users do
       member do #this means you are doing with a certain object
         get :toggle_writer, :as => :toggle_writer_for # this line will generate toggle_writer_for_user_path route
       end
     end
    

Now you can use this route with link_to, like link_to("Toggle writer", toggle_writer_for_user_path(@user)), where @user is you can get from params[:id].

Sergey Kishenin
  • 5,099
  • 3
  • 30
  • 50