用于NilClass的未定义方法'model_name':Class

时间:2012-07-06 10:45:12

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

浏览器在Locals#show中显示以下错误:

NilClass的未定义方法'model_name':Class

51: <%= form_for(@food) do |f| %>
52:   <%= render 'shared/error_messages', object: f.object %>
53:   <div class="field">
54:     <%= f.label :nome %>

这是我的locals_controller.rb(show动作)

 def show
   @local = Local.find(params[:id])
   @foods = @local.foods.paginate(page: params[:page])
   respond_to do |format|
   format.html # show.html.erb
   format.json { render json: @local }
end

这里的foods_controller.rb(创建动作)

def create
@food = @local.foods.build(params[:food])
if @food.save
  flash[:success] = "Food created!"
  redirect_to '/locals'
else
  flash[:error] = "Error on creating food"
  render '/locals'
end
end

食物模型和本地模型与:has_many和belongs_to

相关

问题是什么?谢谢

4 个答案:

答案 0 :(得分:8)

然后将您的视图代码更改为:

<%= form_for :food, :url => {:action => :create} do |f| %>

答案 1 :(得分:2)

通过添加以下代码进行检查(我假设您的模型是本地的)
@food = Local.new
在你的新动作中

答案 2 :(得分:0)

如果您在编辑时发生这种情况,但在创建时它可以正常工作

您必须添加之前的操作并设置食物

       before_action :set_food, only: [:show, :edit, :update, :destroy]

答案 3 :(得分:0)

您可以使用以下任何代码:

<%= form_for :food, :url => {:controller => :food, :action => :create} do |f| %>

<%= form_for :food, url: food_create_path do |f| %>


<%= form_for Food.new , url: food_create_path do |f| %>