NothingToSeeHere
NothingToSeeHere

Reputation: 2363

Setting dynamic link path with url parameters in rails

I'm building an app where I set links dynamically through a url parameter. I can't figure out how to make the link_to work with both a dynamic link and further url parameters.

 TemplateController
   def next
     @template = Template.find(params[:t])
   end 

Next View

 <%= link_to "#{@template.firstpage_link}(:t => @template.id, :prt => 1)" do %><%end%>

This is what it gives me:

 http://localhost:3000/role/step2_path(:t%20=%3E%[email protected],%20:prt%20=%3E%201)

I've tried a bunch of ways and I get either errors or this link

Upvotes: 1

Views: 2531

Answers (2)

Henrik N
Henrik N

Reputation: 16274

What you seem to be shooting for is something like

<%= link_to public_send(@template.firstpage_link, :t => @template.id, :prt => 1) do %>

public_send lets you call a public method by passing in its name as a symbol or string.

However, there may be more elegant ways to achieve this with the Rails router, as @Typpex is suggesting. If nothing else, you could clean up the view a bit with something like this in a helper:

def template_path(template)
  public_send(template.firstpage_link, :t => template.id, :prt => 1)
end

And then calling that from your view.

Upvotes: 2

Typpex
Typpex

Reputation: 608

I think you are not using link_to correctly, if you look at the link_to API

You will see that the first parameter is what you would like to be displayed and the second one is the rails path. You should pass your parameter when defining the rails path (or plain url) such as

link_to "display text", "#{@template.firstpage_link}?t=#{@template.id}&prt=1"

it would be better if you could use a rails route like

template_path(@template, prt: 1)

Upvotes: 0

Related Questions