How do I submit a boolean parameter in Rails?

Viewed 73089

I'm submitting a parameter show_all with the value true. This value isn't associated with a model.

My controller is assigning this parameter to an instance variable:

@show_all = params[:show_all]

However, @show_all.is_a? String, and if @show_all == true always fails.

What values does Rails parse as booleans? How can I explicitly specify that my parameter is a boolean, and not a string?

12 Answers

You could just do

@show_all = params[:show_all].downcase == 'true'

It's worth noting that if you're passing down a value to an ActiveModel in Rails > 5.2, the simpler solution is to use attribute,

class Model
  include ActiveModel::Attributes

  attribute :show_all, :boolean
end

Model.new(show_all: '0').show_all # => false

As can be seen here.


Before 5.2 I use:

class Model
  include ActiveModel::Attributes

  attribute_reader :show_all

  def show_all=(value)
    @show_all = ActiveModel::Type::Boolean.new.cast(value)
  end
end

Model.new(show_all: '0').show_all # => false

While not explicitly what the question is about I feel this is appropriately related; If you're trying to pass true boolean variables in a rails test then you're going to want the following syntax.

post :update, params: { id: user.id }, body: { attribute: true }.to_json, as: :json

I arrived at this thread looking for exactly this syntax, so I hope it helps someone looking for this as well. Credit to Lukom

Related