1

我试图在我的嵌套资源上添加一个销毁按钮并收到此错误: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

谢谢!!!

4

1 回答 1

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

于 2012-05-22T23:20:36.773 回答