开发者

How to pass an optional parameter in link_to?

I have a link like:

<%= link_to 'something', some_path(:param1 => something, :param2 => s开发者_C百科omething) %>

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


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.


You can also do this:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜