Godzilla74 Godzilla74 - 4 months ago 26
Ruby Question

Rails Pass additional parameters in link_to

I was under the impression that it's possible to pass additional parameters within a

link_to
tag in Rails. What I have is a button that a user can click on to move over to another controllers
show
method/view and I need to be able to pass
@network_host.id
to the new controller
issues_controller.rb
, but it's not working. Instead, I get redirected back to my
root_url
.

In order of how the user would do it:



  1. User navigates to www.myserver.com/network_hosts/XX (the show method)

  2. controllers/network_hosts_controller.rb kicks in




class NetworkHostsController < ApplicationController
before_action :set_network_host, only: [:show]

def show
@network_host = NetworkHost.find(params[:id])
if @network_host
@major_issues = get_host_issues(@network_host, @network_host.last_test, "major")
@minor_issues = get_host_issues(@network_host, @network_host.last_test, "minor")
end
end
end




  1. views/network_hosts/show.html.erb (User clicks the link_to button)




<tbody>
<% @major_issues.to_enum.with_index(1).each do |result, index| %>
<% issue = result.issue %>
<tr>
<td>
<%= link_to '<i class="fa fa-eye"></i>'.html_safe, issue_path({ id: issue.id, host: @network_host.id }), "data-toggle" => "tooltip", "title" => "View" %>
</td>
</tr>
<% end %>
</tbody>




  1. Which should then fire controllers/issues_controller.rb (show method, i.e. www.myserver.com/issues/5432),




class IssuesController < ApplicationController
def show
@issue = Issue.find(params[:id])
@network_host = NetworkHost.find(params[:host])
end
end


However, step 4 isn't working, instead it routes back to the homepage. So in my console, I'm looking at what parameters are being passed, and I don't see the
host
parameter:

Started GET "/issues/54387" for 127.0.0.1 at 2016-07-13 14:06:49 -0400
Processing by IssuesController#show as HTML
Parameters: {"id"=>"54387"}


Am I implementing this wrong?

Answer

Your approach is correct, but the host option in your route helper (and all other derivatives of url_for) is reserved for modifying the host in the generated URLs. But since you're using issue_path and not issue_url, the host parameter is just being ignored. To fix your issue, pick another parameter name.

Comments