Rails路由和has_one关系导致错误的路由

时间:2013-02-23 21:36:54

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我有一个用户和内阁模型

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(id的cabinet_ingredient)无法找到......

不确定我为什么会这样......我的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

1 个答案:

答案 0 :(得分:0)

如果有人遇到类似的问题,我提出的解决方案就是:

我没有在cabinet控制器中进行破坏,而是创建了一个cabinet_ingredients控制器并添加了一个destroy动作

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

然后更新了橱柜节目以路由到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