【问题标题】:Instantiating error in Rails applicationRails 应用程序中的实例化错误
【发布时间】:2012-08-12 21:36:30
【问题描述】:

我正在开发一个 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

我(厨师)正在尝试通过转到 /upload 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

但是,一旦我尝试从 /upload url 创建一个菜,我在菜控制器中收到以下错误:

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

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

我想我已经实例化了所有变量,但问题仍然存在。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 model-view-controller controller instantiation


    【解决方案1】:

    在这一行:

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

    chef 变量未实例化。你必须这样做:

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

    这样@chef 变量会在您使用之前填充。

    【讨论】:

    • 我尝试了你的建议,但我得到了一个错误:ActiveRecord::RecordNotFound (Couldn't find Chef without an ID):
    • 检查您的日志以获取传递给控制器​​的厨师 ID 参数。它是params[:id]params[:chef_id] 或类似名称。
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2020-05-23
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多