0

我正在研究Rails應用程序,其中我有兩個模型,即chef模型和dish模型。在Rails應用程序中實例化錯誤

class Dish < ActiveRecord::Base 
    belongs_to :chef 
    attr_accessible :description, :photo, :price 
    validates :chef_id, presence: true 
    has_attached_file :photo 
end 

class Chef < ActiveRecord::Base 
    attr_accessible :name, :email, :mobile ,:password, :password_confirmation, :postcode 
    has_many :dishes 
    has_secure_password 
end 

我(廚師),我試圖通過進入/上傳的URL創建一個菜,他的觀點是

<%= form_for(@dish) do |d| %> 
    <%= d.label :description, "Please name your dish..."%> 
    <%= d.text_field(:description)%> 

    <%= d.label :price, "What should the price of the dish be..."%> 
    <%= d.number_field(:price)%> 

    <%= d.submit "Submit this Dish", class: "btn btn-large btn-primary"%> 
<% end %> 

我想創建的菜出現在廚師的節目頁面上,

<% provide(:title, @chef.name)%>  
    <div class = "row"> 
    <aside class = "span4"> 
     <h1><%= @chef.name %></h1> 
     <h2><%= @chef.dishes%></h2>  
    </aside> 
    <div> 
<% end %> 

而且,dishes_controller是:

class DishesController < ApplicationController 

    def create 
    @dish = chef.dishes.build(params[:dish]) 
    if @dish.save 
     redirect_to chef_path(@chef) 
    else 
     render 'static_pages/home' 
    end 

但只要我嘗試創建從/上傳網址一道菜,我得到以下錯誤在dishes_controller:

NameError undefined local variable or method `chef' for #<DishesController:0x3465494> 

app/controllers/dishes_controller.rb:5:in `create' 

我想我已經實例化的所有變量,但問題仍然存在。

回答

1

在這一行:

@dish = chef.dishes.build(params[:dish]) 

chef該變量沒有實例化。你必須這樣做:

@chef = Chef.find(params[:chef_id]) 
@dish = @chef.dishes.build(params[:dish]) 

這種方式在使用它之前填充了@chef變量。

+0

我嘗試了你的建議,但我得到了這個錯誤:ActiveRecord :: RecordNotFound(找不到沒有ID的廚師): – 2012-08-16 14:33:49

+0

檢查你的日誌中傳遞給控制器​​的廚師ID參數。它是'params [:id]','params [:chef_id]'或類似的東西。 – MurifoX 2012-08-16 16:55:44

相關問題