2013-02-23 45 views
0

我有一個用戶和內閣模型Rails的路線和HAS_ONE關係導致不正確的路線

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 

我不斷收到我的路線,每當我去我的用戶內閣以櫥櫃形式返回.1 ...然後當我嘗試訪問任何cabinet_ingredients時,出現錯誤,說c abinet_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 
+2

呦你不包含有關cabinet_ingredient的任何路由或控制器信息,但問題可能在那裏。如果您在路由中聲明資源而不是資源,那麼只有一個機櫃,所以路由不希望您爲機櫃使用ID。 – 2013-02-23 21:43:14

+0

您能否請您顯示您想要的路線呼叫鏈接? – sailingthoms 2013-02-23 21:43:30

+0

添加了cabinet_ingredient代碼。我沒有內閣成分的路線,我做了內閣的所有工作 – BrianJakovich 2013-02-23 21:52:04

回答

0

如果有人有類似的問題,這裏是這樣的我想出了lution:

而不是做在機櫃控制器的破壞,我創建了一個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_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