views:

145

answers:

5

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?

A: 

Try using attr_accessor

benoror
The param isn't being associated with an object - I'm using it with a custom route generating the following URL: `/statements/compare?show_all=true`
nfm
Didn't see the "This value isn't associated with a model", sorry.
benoror
+1  A: 

You could change your equality statement to:

@show_all == "true"

If you want it to be a boolean you could create a method on the string class to convert a string to a boolean.

benr75
+2  A: 
@show_all = params[:show_all] == "1" ? true : false

This should work nicely if you're passing the value in from a checkbox -- a missing key in a hash generates nil, which evaluates to false in a conditional.

EDIT

As pointed out here, the ternary operator is not necessary, so this can just be:

@show_all = params[:show_all] == "1"

zetetic
+2  A: 

I wanted to comment on zetetic answer but as I can't do that yet I'll post this as an answer.

If you use

@show_all = params[:show_all] == "1" ? true : false

then you can drop ? true : false because params[:show_all] == "1" statement itself will evaluate to true or false and thus ternary operator is not needed.

Uģis Ozols
Good point! I updated my answer to reflect that.
zetetic
+1  A: 

This works just fine

@show_all = params[:show_all]

provided you test like this

if @show_all

don't bother with tests, ruby is very strict about what equalates to a true value. Anything other than false or nil is true. This means 0 and "" are true in ruby unlike other languages.

epochwolf
Nice! Changing my accepted answer :P
nfm
I recommend learning a bit about ruby before driving head first into rails. :) Makes learning rails easier.
epochwolf