Reputation: 3904
I have a model name "profit" and it has a table name profits and 3 column of the table "product_id", "client_id", "grossprofit"
Now in my index.html.erb page I have option for show as
<td><%= link_to 'Show', profit %></td>
when I click on the show link i go to show page and link become
http://localhost:3000/profits/1
http://localhost:3000/profits/2
that is i am getting id of profits table but I need product_id and client_id in my url like below
http://localhost:3000/profits/3/5
where 3 will be product_id and 5 will be client_id
What changes I have to do to get this url and how can I get product_id and client_id from the url in show action of the controller?
Association among the models are
product: has_many profits
client: has_many profits
profit: belongs to product and client
Upvotes: 0
Views: 134
Reputation: 76784
Routes
As HarsHarl & cenyongh suggested, you'd be better looking at Nested Resources
The problem you've got is that you can't access the product_id
and client_id
vars, unless they're stored in a session. Because of this, you'll have to pass them through the URL
I'd use this:
resources :profits do
get ":product_id/:client_id", to: "show"
end
This will create this route:
/profits/13/5
More importantly, it will pass these params: product_id
and client_id
to the show action
Upvotes: 0
Reputation: 1692
The routes.rb
resources :profits do
get ":product_id/:client_id", :action => :show, :as => :show, :on => :collection
end
The view
<%= link_to 'Show', show_profits_path(profit.product_id, profit.client_id) %>
The development log when clicking the link is
Started GET "/profits/5/3" for 127.0.0.1 at 2014-01-04 20:42:10 +0800
Processing by ProfitsController#show as HTML
Parameters: {"product_id"=>"5", "client_id"=>"3"}
Upvotes: 1
Reputation: 911
you make wrong routes in routes.rb file please declare it as :
resources :profits do
resources :products, :clients
end
Upvotes: 1