How to embed variables in a link_to

Hello,
I’m just trying to figure out how to put a variable into a link_to. I
want to have the number of rows from my SQL statement in it. For
example:

perfect matches (123)

where 123 is the number of rows. I currently have the number of rows in
an array, but it just displays rows[pm_rows] (when I put rows[‘pm_rows’]
it kicks a compile error due to the quotes) because its in
quotations… how can I escape this? My link_to looks like this:

<%= link_to ‘perfect matches (rows[pm_rows])’, :controller => ‘compare’,
:action => ‘perfectmatches’ %>

Any help is appreciated!

Thank you!

  • Jeff M.

Jeff M. wrote:

Hello,
I’m just trying to figure out how to put a variable into a link_to. I
want to have the number of rows from my SQL statement in it. For
example:

perfect matches (123)

where 123 is the number of rows. I currently have the number of rows in
an array, but it just displays rows[pm_rows] (when I put rows[‘pm_rows’]
it kicks a compile error due to the quotes) because its in
quotations… how can I escape this? My link_to looks like this:

<%= link_to ‘perfect matches (rows[pm_rows])’, :controller => ‘compare’,
:action => ‘perfectmatches’ %>

Any help is appreciated!

Thank you!

  • Jeff M.

Hi Jeff,
You don’t send the parameters as if it was a function call. Instead,
you set some arbitrary hash key to the value in question in the URL part
of the link_to, and then inside the link’ed to action you access it
through the “params” with the key you gave it:

<%= link_to ‘perfect matches’,
:url => {:controller => ‘compare’,
:action => ‘perfectmatches’,
:my_rows => rows[pm_rows]}
%>

def perfectmatches
my_rows = params[:my_rows]

end

HTH,
jp

“#{@myvar}”

Http://www.rubyplus.org
Free Ruby & Rails screencasts

On Feb 16, 2008, at 4:07 PM, Jeff M.
<[email protected]

Hello,
Thanks for your response! The thing is, I’m trying to get this variable
into the link text, not trying to send it somewhere. My controller comes
up with the number of rows and I want to put it in the link text so it
would read something like “perfect matches (200)” where 200 would be
rows[‘pm_rows’]… The quotes just kill it each time though… Any
suggestions?

I got it to work, thanks!

<% for rows in @pm_rows %>
<%= link_to “perfect matches (#{rows[‘pmrows’]})”, :controller =>
‘compare’, :action => ‘index’ %>
<% end %>