0

我有一个用户和机柜模型

class User < ActiveRecord::Base

  has_one :cabinet

  after_create :create_cabinet

  // Omitted code

  def create_cabinet
    Cabinet.create(user_id: id)
  end
end

-

class Cabinet < ActiveRecord::Base

  has_many :cabinet_ingredients, :dependent => :destroy
  has_many :ingredients, through: :cabinet_ingredients
  belongs_to :user

  attr_accessible :user_id, :cabinet_ingredients_attributes

  accepts_nested_attributes_for :cabinet_ingredients

end

-

Mixology::Application.routes.draw do

  // Omitted code
  resource  :cabinet

end

每当我去我的用户柜以作为cabinet.1 回来时,我都会不断获得我的路线......然后当我尝试访问任何cabinet_ingredients 时,我收到一个错误,提示cabinet_ingredient.5(cabinet_ingredient 的id)不能被发现...

不知道为什么我会得到这个.. 我的rake routes回报:

    cabinet     POST   /cabinet(.:format)                 cabinets#create
    new_cabinet GET    /cabinet/new(.:format)             cabinets#new
   edit_cabinet GET    /cabinet/edit(.:format)            cabinets#edit
                GET    /cabinet(.:format)                 cabinets#show
                PUT    /cabinet(.:format)                 cabinets#update
                DELETE /cabinet(.:format)                 cabinets#destroy

橱柜展示视图

%table.table.table-striped
  %thead
    %tr
      %th My Ingredients
      %th ID
  %tbody
    - @cabinet.cabinet_ingredients.each do |ci|
      %tr
        %td= ci.ingredient.name
        %td= link_to "delete from cabinet", cabinet_path(ci), method: :delete, confirm: "Are you sure?"

机柜控制器:

  def show
    @cabinet = current_user.cabinet
  end

  def edit
    @cabinet = current_user.cabinet
    @ingredients = Ingredient.all
  end

  def update
    @ingredients = Ingredient.all
    @cabinet = current_user.cabinet
    if @cabinet.update_attributes(params[:cabinet])
      redirect_to @cabinet
    else
      render 'edit'
    end
  end

  def destroy
    ingredient = CabinetIngredient.find(params[:id])
    ingredient.destroy
    redirect_to cabinet_path
  end
4

1 回答 1

0

如果有人有类似的问题,这是我想出的解决方案:

我没有在橱柜控制器中进行销毁,而是创建了一个 cabinet_ingredients 控制器并添加了一个销毁操作

class CabinetIngredientsController < ApplicationController
  def destroy
    ingredient = current_user.cabinet.cabinet_ingredients.find(params[:id])
    ingredient.destroy
    redirect_to cabinet_path
  end
end

然后更新cabinet show 以路由到cabinet_ingredients 控制器

%table.table.table-striped
  %thead
    %tr
      %th My Ingredients
      %th ID
  %tbody
    - @cabinet.cabinet_ingredients.each do |ci|
      %tr
        %td= ci.ingredient.name
        %td= link_to "delete from cabinet", cabinet_ingredient_path(ci), method: :delete, confirm: "Are you sure?"

最后是路线:

Mixology::Application.routes.draw do

  resource  :cabinet
  resources :cabinet_ingredients

end
于 2013-02-23T22:14:53.403 回答