[ruby-on-rails] Rails - passing parameters in link_to

My Accounts index page lists all accounts, and per account has a link to "+ Service"; this should direct the user to the /my_services/new page and have pre-populated the account_id field with the appropriate ID, depending on which link was clicked on the Accounts index page.

I have debug(params) at the bottom of every page, and with what I'm trying, I'm not getting anything other than :controller and :action showing up in my parameters for the /my_services/new page.

The link I've been trying is this:

link_to "+ Service", "my_services/new", :account_id => acct.id

I then also have logic in the services controller:

def new
  @my_service = MyService.new
  if params[:account_id]
    @my_service.account_id = params[:account_id]
  end
end

Can someone help with the proper way of doing this? I haven't yet been able to get it going with with a few nasty little hacky things I tried.

EDIT

Turns out, if someone is looking at this answer in future, nested resources (possibly with the shallow: true option in routes.rb) seem to be the way to go. My routes.rb for this part now looks like this:

resources :accounts, shallow: true do
  resources :services
end

My links now look like this:

<%= link_to "+ Service", new_service_path(:service => { :account_id => @account.id } ) %>

This question is related to ruby-on-rails

The answer is


Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to


link_to "+ Service", controller_action_path(:account_id => acct.id)

If it is still not working check the path:

$ rake routes