Reputation: 11
I have a Group model, which has many lists.
Group
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
has_many :lists
accepts_nested_attributes_for :lists
cattr_accessor :current_user
end
List
class List < ApplicationRecord
belongs_to :group
validates_presence_of :group_id
end
I iterate over @group.lists
<% @group.lists.each do |elem| %>
<p><strong><%= elem.title %></strong></p>
<p><%= elem.body %></p>
<%= link_to 'Delete list', [elem.group, elem], method: :delete,
data: {confirm: "Are you sure?"} %>
<%= link_to 'Update list', edit_group_list_path(:group_id => @group.id, :list_id => elem.id), method: :put %>
<% end %>
Delete method works good, but update method works wrong. Instead of creating links like http://localhost:3000/groups/9/lists/10/ where group_id is 9 and list_id is 10, it's doing something like this http://localhost:3000/groups/9/lists/9/edit?list_id=15
Routes:
resources :groups do
resources :lists
end
Upvotes: 0
Views: 35
Reputation: 3513
As @Ursus said, the default behavior of nested resources in rails to to accept a plain :id
parameter for the innermost resource, /groups/:group_id/lists/:id
. You can also simply pass in the objects directly instead of mapping to ID integers:
edit_group_list_path(@group, elem)
You can read more about nested resources here: http://guides.rubyonrails.org/routing.html#nested-resources
Upvotes: 1
Reputation: 30071
Run
rails routes
to understand where you are wrong
Anyway, the nested resource requires just id
, so
edit_group_list_path(:group_id => @group.id, :id => elem.id)
Any other parameter is added in query string
Upvotes: 1