4

浏览器在 Locals#show 中返回了以下错误:

NilClass:Class 的未定义方法“model_name”

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 (显示操作)

 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

结尾

这里 food_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

Food 模型和 Local 模型与 :has_many 和 belongs_to 相关

有什么问题?谢谢

4

4 回答 4

8

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

<%= form_for :food, :url => {:action => :create} do |f| %>
于 2012-07-06T11:56:39.530 回答
2

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

于 2012-07-06T11:23:11.930 回答
0

如果在您编辑时发生这种情况,但在您创建时它有效

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

       before_action :set_food, only: [:show, :edit, :update, :destroy]
于 2014-02-02T01:42:42.333 回答
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| %>
于 2016-05-05T11:04:34.977 回答