rails params.merge in link_to

2019-08-04 05:16发布

问题:

I am trying to add a URL parameter in a link_to block.

The code currently <%= link_to "Submit", :action => 'renderChart', :class => "btn", :remote => true, :params => params.merge(:limit => 5) %>

but this gives me an error.

It adds the :class and :action into the url parameter, not just the :limit. Why?

EDIT:

I add other URL params from another link that looks like this

link_to "Toggle Sort Direction",:action => 'renderChart', :remote => true, :params => {:sort => "desc"}

so when the user clicks the other link I want to add the limit to the url params and keep the sort params

回答1:

I finally managed to get a solution myself.

If I very simply do this: :params => {:limit => ..., :sort => params[:sort]} i get exactly what I need. If there is a sort param it keeps it the way it is.



回答2:

Use this

<%= link_to "Submit",{ :action => 'renderChart', :remote => true, :limit => 5, :sort => "desc"}, :class => "btn" %>

Separate out the html_options: class is an html_option so pass it last.

Refer to link_to documentation.

UPDATE

As per the OP's concern in EDIT section of Question:

I add other URL params from another link that looks like this

link_to "Toggle Sort Direction",:action => 'renderChart', :remote => true, :params => {:sort => "desc"}

params :sort => "desc" are for Toggle Sort Direction link and they cannot be connected to the Submit link. When you click on a particular link, params specified in the link would be added to the params hash. So, if you need to pass :sort => "desc" as params upon clicking on Submit link then specify them explicitly as shown in my answer above.



回答3:

You need to explicitly separate the hashes:

<%= link_to "Submit", { :action => 'renderChart', :class => "btn", :remote => true }, params.merge(:limit => 5) %>

Take the link_to out and you have an implicit hash (key-value pairs) and Ruby is smart enough to know you want a hash:

:action => 'renderChart', :class => "btn", :remote => true, params.merge(:limit => 5)

But that last thing - that's not a key-value pair - it's a hash. So really, you have this:

{ :action => 'renderChart', :class => "btn", :remote => true, { ... } }

If you take Rails out of the mix:

{ x: 'value', {} }

And that's simply not a valid Hash :)