Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More-efficient way to pass the Rails params hash to named route

I need a more-efficient way to pass the params hash to a named route, including the ability to add/remove/modify a key/value pair.

Adding a key (the :company symbol), while preserving the remainder of the params hash (manually specify each symbol/value):

# adds the company filter
link_to_unless params[:company]==company, company, jobs_path(:company=>company, :posted=>params[:posted],:sort=>params[:sort],:dir=>params[:dir])

Removing a key (eliminates the :company symbol), while preserving the remainder of the params hash (manually specify each symbol/value):

# create a link that removes the company filter
link_to_unless_current 'x', jobs_path(:posted=>params[:posted],:sort=>params[:sort],:dir=>params[:dir])

I thought of just passing the params hash directly, but that throws an exception:

link_to_unless params[:company]==company, company, jobs_path( params )

I'm hoping for some DRYer alternatives.

like image 955
craig Avatar asked Dec 05 '25 10:12

craig


1 Answers

Refactored the helper function:

def options(hash)
    o={:employer=>params[:employer],:location=>params[:location],:posted=>params[:posted],:starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]}
    # add the contents of hash, overwriting entries with duplicate keys 
    o.merge!(hash)
end

Refactored the view code to pass hash instead of key/value pair; greater flexibility:

<%= link_to_unless params[:employer]==employer, employer, jobs_path( options({:employer=>employer}) ) %>

and

<%= link_to_unless_current '✗', jobs_path( options({:employer=>nil}) ) %>
like image 200
craig Avatar answered Dec 07 '25 19:12

craig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!