user5429202
user5429202

Reputation:

Setting a variable within a link_to, in rails 4

I am trying to set variables in a series of link_to links, so that each link is associated with a value.


On one page I have a loop which creates a list of links from values in my database:

<ul>
  <% @alldata.each do |x| %>
    <li><%= link_to "#{x.name}", charts_path %></li>
  <% end %>
</ul>

The charts_path links to a view which displays a chartkick graph:

<%= line_chart @data.group("year").sum("magnitude") %>

which gets its data from a controller saying:

def graphdata(x)
  @data = Model.all.where(name: x).select("magnitude, year")
end

def charts(?variable)
  @data = graphdata(?variable)
end

I would like to alter my list loop to set ?variable to x.name. For example something like:

<li><%= link_to "#{x.name}", charts_path, ?variable = "#{x.name}" %></li>

So that I have a list of links, that route to different charts with data specific to that link.


I could define a specific view for every single name:

def chart1
  @data = graphdata("name1")
end

def chart2
  @data = graphdata("name2")
end 

But that seems like very bad programming...


I'm sorry if this question is poor, I'm extremely new to programming.

Any assistance would be greatly appreciated!

Thank you

Upvotes: 1

Views: 1578

Answers (3)

kiruthika
kiruthika

Reputation: 89

I encountered the similar state where I got my module worked with the following method

`<%= link_to n.subject, notifications_message_path(notification_id: n.id)%>`

Upvotes: 0

maniacalrobot
maniacalrobot

Reputation: 2463

If I understand correctly, you want to pass the name of x as a querystring variable. You can easily do this with the charts_path helper:

<%= link_to "#{x.name}", charts_path(variable: x.name) %>

charts_path accepts a hash that will be passed with the request

Upvotes: 0

kajal ojha
kajal ojha

Reputation: 1278

Try Using this Code.

<%= link_to "#{x.name}", charts_path(x.name) %>

Upvotes: 3

Related Questions