Ruby on Rails: use variable in link_to helper path

I have a partial part of HAML that receives a variable bar, and I would like to introduce this variable in the link_to path.

For example:

= link_to new_foo_path, class: 'source card' do
    .stuff

I want to replace foo with bar.

I tried:

= link_to new_#{bar}_path, class: 'source card' do

and a dozen other things, but nothing works.

Thoughts?

+4
source share
4 answers

You can try this as follows:

link_to send("new_#{bar}_path"), class: "source card" do

Basically, send does something by a method or variable, and allows you to combine everything in this line into one variable.

+7
source

I encountered a similar situation, so I created a view helper. For your case, I think you can do something like this.

helpers/application_helper.rb:

def custom_path pathvar
   if pathvar == 'foo'
      new_foo_path
   elsif pathvar == 'bar'
      new_bar_path
   end
end

, , :

= link_to custom_path(bar), class: 'source card' do

. .

+1

You can add parameters to the link helper as follows:

link_to "New Foo", new_foo_path(bar: "bar")
0
source

I think you can use eval:

= link_to eval("new_#{bar}_path"), class: 'source card' do
0
source

All Articles