0

I uses Rails erb to create links, like the following:

<% link_to item_path(topic.company, topic, :area => params[:area]) do %>

However now I need to add some condition, when it fulfills I want to pass additional parameters to the item_path function. like:

<% link_to item_path(topic.company, topic, :area => params[:area], :utm_source => "top") do %>

I guess Ruby probably has a way to add additional parameters since parameter passing is essentially a hash right? Is there an cool way to do this, instead of an if-else statement calling item_path with different set of parameters (like in Java?).

P.S. I tried have one extra hash with the additional parameter and append it into the functional call, like the following. But it didn't work.

<% link_to item_path(topic.company, topic, :area => params[:area], additional_param) do %>

2 Answers 2

1

Build your arguments hash before calling link_to:

<% args = { :area => params[:area] } %>
<% args[:utm_source] = 'top' if(whatever) %>
<%= link_to item_path(topic.company, topic, args) do %>
    <!-- ... -->
<% end %>

When you call a method like this:

o.m :where => 'is', :pancakes => 'house?'

Ruby automatically wraps the arguments in a hash so the above is the same as:

o.m { :where => 'is', :pancakes => 'house?' }

or even

h = { :where => 'is', :pancakes => 'house?' }
o.m h
Sign up to request clarification or add additional context in comments.

4 Comments

also it seems like the params hash building code probably belongs in the controller or a helper method, not in the view
@Matthew: Probably but hard to say without more context.
thanks. I used Hash.merge! on top of this. About MVC, it is in a partial so a bit difficult to do that
@lulalala: My Probably above probably should have been Possibly. And merge! or assignments are fine, whatever works and is clearest to you.
1

You can try this:

link_to item_path(topic.company, topic, :area => params[:area],
  :utm_source => ("top" if top?), :abc => (1 if bottom?))

The values for the hash keys will be set nil when the if condition is NOT met. The path helpers ignore the hash keys with nil values.

2 Comments

Thanks, I would definitely use this when only one additional parameter is needed.
This trick works well with path helpers only. The path helpers ignore the nil values. eg: experts_path(:age=>2, :foo=>nil) results in experts?age=2 instead of experts?age=2&foo=nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.