我正在开发一个Rails应用程序,其中我有两个模型,即chef
模型和dish
模型。
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
我(厨师)正试图通过转到/上传网址创建一个菜,其视图是
<%= 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
但是当我尝试从/ upload url创建一个菜时,我在dishes_controller中收到以下错误:
NameError undefined local variable or method `chef' for #<DishesController:0x3465494>
app/controllers/dishes_controller.rb:5:in `create'
我想我已经实例化了所有变量,但问题仍然存在。
答案 0 :(得分:1)
在这一行:
@dish = chef.dishes.build(params[:dish])
chef
变量未实例化。你必须做这样的事情:
@chef = Chef.find(params[:chef_id])
@dish = @chef.dishes.build(params[:dish])
这样在使用@chef变量之前就会填充它。