Coda Chang Coda Chang - 4 months ago 9
Ruby Question

Rails routing many to one

I thought it's a simple question, but I was just stuck here.

I have two model

Category
and
Project
, and
Category
has many
Project
.

Then, I thought there would be a route like

http://localhost:3000/categories/1872/projects/499, the
1872
will be category' id and
499
will be project's id. The page would display information of the project.

So, I wrote this in
routes.rb


get '/categories/:id/projects/:id', to: 'projects#show', as: 'project'


In category's show page, I wrote

<% @category.projects.each do |project| %>
<h1>
<%= link_to "#{project.name}", project %>
</h1>
<% end %>


But the link I create will be http://localhost:3000/categories/499/projects/499

Update



I've changed routes into

resources :categories, only: [:index, :show] do
resources :projects, only: [:show]
end


But, I don't know how to write
link_to
path in category's show page.

I wrote this

<% @category.projects.each do |project| %>
<%= link_to "#{project.name}", category_project_path %>
<% end %>


But it threw this error

No route matches {:action=>"show", :controller=>"projects", :id=>"1982"} missing required keys: [:category_id]

Answer

You should use Nested Routing for this and I recommend using resources, just write:

resources :categories do
  resources :projects
end

You can read more here Rails Routing from the Outside In

UPDATED:

To correctly link that route, you need to use just the project path <%= link_to "#{project.name}", project_path(project) %>

or use category_project_path like <%= link_to "#{project.name}", category_project_path(category, project) %>