我试图在嵌套资源上添加一个销毁按钮并收到此错误:No route matches [DELETE] "/users/1/2/4/5/holidays/7"
以下是我的观点,路线,模型和相关部分。控制器:
<% @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 %>
路线
resources :users do
resources :interests
resources :holidays
end
模型
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
控制器
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
感谢!!!
答案 0 :(得分:2)
改变这个:
<%= button_to('Destroy', user_holiday_path(@user.holidays), :method => 'delete', :class => 'btn btn-large btn-primary') %>
对此:
<%= button_to('Destroy', user_holiday_path(h), :method => 'delete', :class => 'btn btn-large btn-primary') %>
更新
更改您的销毁行动:
@holiday = Holiday.find(params[:id])
到
@user_holiday = UserHoliday.find(params[:id])
并在您看来:
改变
<% @user.holidays.each do |h| %>
到
<% @user.user_holidays.each do |h| %>
您的协会需要进行一些更正,并且应如下:
user has_many user_holidays
user_holiday has_one holiday
user_holidays belongs_to user
您可以通过h对象访问姓名和假期:
h.holiday.name
h.holiday.date