Best practise for setting default URL parameters in the controller

I’ve been trying to set default URL parameters in the controller, which will also be used within the view. This is what I’ve got:

@params = params

defaults = { :date_from => ‘21/1/21014’, :date_to => ‘21/2/21014’, :data=>“Expense” } if @params.any? @params = defaults.merge(@params) else @params = defaults end

… seems messy, and doesn’t work :frowning: When params are present it still uses the default params. Not sure where it’s going wrong and search on google yields many varieties. I know using default values in methods is something that I will repeat again so I was wondering what the best practise is for handling this. Thanks

That is likely because it should be params not @params. I don't think you need the .any? test either, just let it merge the empty hash into defaults.

If you need to do this in more than one controller method then use a before filter.

Colin

It doesn't work because @params isn't where params are stored. Params is never empty (at a minimum :controller and :action are set) so you can get rid of the else

You could update params in place , ie params.merge!(...).

Personally I wouldn't do this. I'd be more likely to have a controller method called something like get_date_range that would get the dates from params that would do things like parse the strings into actual dates and/or replace missing params with defaults.

Fred

... You could update params in place , ie params.merge!(...).

Would that not use the value from defaults if it was already present in params?

Personally I wouldn't do this. I'd be more likely to have a controller method called something like get_date_range that would get the dates from params that would do things like parse the strings into actual dates and/or replace missing params with defaults.

+1

Colin

> ...

> You could update params in place , ie params.merge!(...).

Would that not use the value from defaults if it was already present in params?

I was assuming this was after checking that params didn't have the values in question, although if not you could use reverse_merge!

Fred

That is likely because it should be params not @params.

But:

....

This is what I've got:

@params = params

so @params should work the same as params. Not sure why he's bothering to copy it into an @-var, tho; maybe he wants access to it in a view....

-Dave

Personally, I'd say "best practice" is "don't do that" :slight_smile:

Instead of passing raw params to a view, build your model object (or a service object) with them and pass that in. And if you need defaults for missing attributes specified, the model/s.o. would be a better place for them.

FWIW,