Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an optional parameter in link_to?

I have a link like:

<%= link_to 'something', some_path(:param1 => something, :param2 => something) %>

How can I make param2 optional? I want to include it based on a condition.

like image 636
Martin Petrov Avatar asked May 08 '11 20:05

Martin Petrov


3 Answers

Try this:

Approach 1

<%= link_to 'something', some_path(
  {:param1 => something}.merge((x==1) ? {:param2 => something} : {}) %>

Approach 2

<%= link_to 'something', some_path(:param1 => 1, :param2 => (2 if x==1)) %>

In the above example when x equals to 1, the param2 key value is nil. The link_to method ignores the nil valued keys.

like image 130
Harish Shetty Avatar answered Nov 01 '22 10:11

Harish Shetty


You can also do this:

<%= link_to 'something', some_path(:param1 => 'something', :param2 => ('something else' if some_condition)) %>
like image 4
MrRuru Avatar answered Nov 01 '22 11:11

MrRuru


I can suggest you to use a hash here if there is many condition based options:

<% params = {}
   params[:param1] => "blah-blah" if condition
   params[:param2] => "blah-blah" if condition
   params[:param3] => "blah-blah" if condition
   params[:param4] => "blah-blah" if condition
   params[:param5] => "blah-blah" if condition %>
<%= link_to 'something', some_path(params) %>

It is good idea to wrap it as a helper

like image 2
fl00r Avatar answered Nov 01 '22 10:11

fl00r