Dan Rubio
Dan Rubio

Reputation: 4907

Why can't I pass params into link_to onto controller?

I have the following link_to method in my haml view:

= link_to(t('compare.view_as_graph'), compare_graph_projects_url, remote: true)

When I click this link, I want the params of my url which has this extension:

p/compare?project_0=MySQL&project_1=fast-math

to pass into a compare_controller that I've created with the following code inside of it.

def projects_graph
  respond_to do |format|
    format.js
  end
end

Currently the code gives me this params hash when I inspect it:

{"controller"=>"compare", "action"=>"projects_graph", "query"=>nil}

This is not what I need. I need the project_0 and project_1 portions. This is my route from routes.rb

 get 'p/graph', to: 'compare#projects_graph', as: :compare_graph_projects

I've tried a number of things such as this

compare_graph_projects_url(params)
compare_graph_projects_url(opts[:graph])
= link_to(t('compare.view_as_graph'), compare_graph_projects_url, data: {params: params}, remote: true)

(The opts[:graph] was a variable in haml that contains the params)

What am I doing wrong here? Why can't I grab the params with the AJAX request?

The only other thing that I can think of was doing request.referer to get the actual header information but this doesn't seem very railsy. Help would be appreciated.

Upvotes: 1

Views: 350

Answers (2)

badawym
badawym

Reputation: 1509

You should pass your parameters to the route helper like this:

compare_graph_projects_url(project_0: opts[:graph][project_0], project_1: opts[:graph][project_0])

Upvotes: 2

Mandeep
Mandeep

Reputation: 9173

You just need to pass in the values inside url helper like this:

= link_to(t('compare.view_as_graph'), compare_graph_projects_url(project_0: "Your value", project_1: "your value"), remote: true)

Then you can access them in controller like this:

def projects_graph
  @proj_0 = params[:project_0]
  @proj_1 = params[:project_1]
end

You should also read about action controllers for more details on how things work.

Upvotes: 2

Related Questions