Reputation: 1314
Im trying to add a destroy button on my nested resource and getting this error: No route matches [DELETE] "/users/1/2/4/5/holidays/7"
Heres the relevant parts of my view,routes, models, & controllers:
<% @user.holidays.each do |h| %>
<td><%= h.name %></td>
<td><%= h.date %></td>
<td>
<%= button_to('Destroy', user_holiday_path(@user.holidays), :method => 'delete', :class => 'btn btn-large btn-primary') %>
</td>
<% end %>
Routes
resources :users do
resources :interests
resources :holidays
end
Models
class User < ActiveRecord::Base
has_many :holidays, :through => :user_holidays
end
class UserHoliday < ActiveRecord::Base
attr_accessible :holiday_id, :user_id
belongs_to :user
belongs_to :holiday
end
class Holiday < ActiveRecord::Base
attr_accessible :name, :date
has_many :user_holidays
has_many :users, :through => :user_holidays
end
Controller
class HolidaysController < ApplicationController
def index
@user_holidays = Holiday.find(params[:user_id])
@holidays = @user_holidays.holidays
end
def new
end
def show
@holiday = Holiday.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @holiday }
end
end
def destroy
@holiday = Holiday.find(params[:id])
@holiday.destroy
end
end
Thanks!!!
Upvotes: 1
Views: 4776
Reputation: 6948
Change this :
<%= button_to('Destroy', user_holiday_path(@user.holidays), :method => 'delete', :class => 'btn btn-large btn-primary') %>
to this:
<%= button_to('Destroy', user_holiday_path(h), :method => 'delete', :class => 'btn btn-large btn-primary') %>
Update
Change your destroy action from :
@holiday = Holiday.find(params[:id])
to
@user_holiday = UserHoliday.find(params[:id])
and in your view:
change
<% @user.holidays.each do |h| %>
to
<% @user.user_holidays.each do |h| %>
Your associations need some correction and should be as follows:
user has_many user_holidays
user_holiday has_one holiday
user_holidays belongs_to user
You can access name and holiday via your h object:
h.holiday.name
h.holiday.date
Upvotes: 2