sai
sai

Reputation: 396

passing boolean parameters to named routes in rails

I want to explicitly pass a boolean false to params[:closed] and I've got something like this:

= link_to 'appointments', appointments_path(:closed => false)

But this is not working as rails is treating a false boolean as I don't want anything set for this params, is there any way to get around this?

update: the false I'm passing in is a boolean and I want an url like this

\appointments?closed=false

but all I get is just \appointments. Hope this is a bit more clear.

Side question, is it good practise to pass booleans as params?

Upvotes: 1

Views: 3971

Answers (3)

user151339
user151339

Reputation: 41

It sounds like you need 3 different options. Closed not selected, closed set to true or set to false.

If you need to distinguish closed from not being selected and being set to false like this you'll need to just use strings and params[:closed] == 'false'. If rails had some catch that would translate a url string to a boolean you wouldn't be able to pass the string "false" as a parameter which would be weird.

If your closed parameter was ALWAYS going to be true or false (without a not selected option) then doing it like you're doing is fine.

You specify it in the _path method with :closed => true or :closed => false and then test it with params[:closed] as in:

if params[:closed]
  blah
else
  other_blah
end

Upvotes: 0

ry.
ry.

Reputation: 8055

Probably too late now, but try using a string instead:

appointments_path(:closed => 'false')

Upvotes: 3

August Lilleaas
August Lilleaas

Reputation: 54593

That will result in ?closed=false. params[:closed] will then return "false", which is a string, and will evaluate to true.

I would have used named routes for this, instead of manic if/else checking in the 'index' action.

# routes.rb
map.resources :appointments, :collection => {:closed => :get, :open => :get}

# controller
def closed
  @appointments = Appointment.closed
end

def open
  @appointments = Appointment.open
end

Upvotes: 0

Related Questions