YLim
YLim

Reputation: 255

How to pass down parameter using link_to

<td><%= link_to "See Chart", "#AddChartModal" %> </td>

<%= render partial: 'searches/chart', locals: {senid: sensor.id} %>

Like the code above, I'll like to pass down @sensors to another controller.

<td><%= link_to "Results", "folder_name/file_name" %> </td>

Is there a way to pass down @sensors using link_to to another controller?

Upvotes: 0

Views: 80

Answers (3)

Saif Chaudhry
Saif Chaudhry

Reputation: 451

<%= link_to "See Chart", "chart_path(sensor_id: @sensor.id)" %>

This is how you can pass sensor id to chart controller.

Upvotes: 0

jvillian
jvillian

Reputation: 20253

Assuming you have @sensors that is an enumerable that responds to ids. And also assuming in your routes.rb, you have something like:

Rails.application.routes.draw do
  resources :results
end

...then you could do something like:

<td><%= link_to "Results", results_path(sensor_ids: @sensor.ids) %> </td>

Which will give you something like:

<a href="/results?sensor_ids%5B%5D=3&sensor_ids%5B%5D=4">Results</a>

When you click on the link, you'll have something like:

Started GET "/results?sensor_ids%5B%5D=3&sensor_ids%5B%5D=4" for ::1 at 2019-08-20 21:36:50 -0700
Processing by ResultsController#index as HTML
  Parameters: {"sensor_ids"=>["3", "4"]}

In your ResultsController, then, you can do something like:

#app/controllers/results_controller.rb
class ResultsController < ApplicationController

  def index
    @sensors = Sensor.where(id: params[:sensor_ids])
    ...
  end

end

...and now you'll have @sensors in your ResultsController.

Upvotes: 2

Jonathan Bennett
Jonathan Bennett

Reputation: 1065

<%= link_to "Results", results_path(senid: sensor.id) %> would give you a link to something like /results?senid=123

Upvotes: 0

Related Questions