Changing a Boolean Value Using a Rails Link

This took some serious Googling, but it has been useful in so many different projects.

Tags: Ruby on Rails

Back to Blogs

The first order of business here is to create the definition of the method within the controller for whatever change you're trying to make. So, if you're trying to authorize a user then you would create something like the following:

class UsersController < ApplicationController
    def authorize
        @user = User.find(params[:id])
        if @user.update_attributes(authorized: true)
            redirect_to :back
            flash[:notice] = "That user has been authorized!"
            redirect_to root_path
            flash[:warning] = "Oops! Something went wrong!"

It used to be update_attribute in previous Rails versions, but at least with Rails 4 the plural is important or you'll get an error saying wrong number of arguments (given 1, expected 2).

Then the new route needs to be added to routes.rb:

  post "users/:id/authorize" => "users#authorize", as: "authorize"

There is a Stack Overflow post that deals with this same issue that says to use match instead of post, but this will now throw up an error to choose either post or get, and in this instance we want to post the information to the database, so there we go.

Lastly, the link to use in a view would be something like this:

<%= link_to "Authorize User", authorize_path(@user), method: :post %>

The method: :post is necessary so it understands that you want to post the information to the database.

And there we go! I use this for archiving/unarchiving, marking things read/unread, and a variety of other useful boolean goodies.

Back to Blogs