Rails简单形式未定义方法`model_name'为零:NilClass

时间:2016-05-15 10:48:58

标签: ruby-on-rails ruby simple-form-for

我想创建一个简单的表单,对已经发布在食谱中的食谱进行新的评论。我在食谱展示页面上呈现了评论表单,但它一直给我同样的错误:

未定义的方法`model_name'为零:NilClass

如果我不在 app / views / recipes / show.html.erb 中呈现部分新审核表单,而是创建文件 app / views / reviews / new。 html.erb ,只有表单才有效。当我尝试在show recipe页面渲染时,我不明白为什么表单不起作用。

这是我的代码:

简单形式:

<%= simple_form_for(@review, url: recipe_reviews_path(@recipe)) do |f| %>
    <%= f.error_notification %>
    <%= f.input :content %>
    <%= f.input :rating %>
    <%= f.button :submit, class: "btn btn-success" %>
<% end %>

评论控制器:

class ReviewsController < ApplicationController
  def new
    @recipe = recipe.find(params[:recipe_id])
    @review = Review.new(review_params)
  end

  def create
    @recipe = recipe.find(params[:recipe_id])
    @review = Review.new(review_params)
    @review.recipe = @recipe
    if @review.save
      redirect_to recipe_path(@recipe)
    else
      render 'recipe/show'
    end
  end

  private

  def review_params
    params.require(:review).permit(:content, :rating)
  end
end

食谱控制器:

class RecipesController < ApplicationController
  skip_before_action :authenticate_user!
  def index
    @recipes = Recipe.all
  end

  def show
    @recipe = Recipe.find(params[:id])
    @user = User.find(@recipe.user_id)
    @full_name = @recipe.user.first_name + " " + @recipe.user.last_name
  end
end

食谱展示页面:

<div class="review">
  <%= render 'review/new' %>

  <% @recipe.reviews.each do |review| %>
      <%= review.content %>
      <%= review.rating %>
  <% end %>
</div>

路线:

 resources :recipes, only: [:index, :show] do
    resources :reviews, only: [:create]
  end

型号:

class Recipe < ActiveRecord::Base
  belongs_to :user
  has_many :ingredients, dependent: :destroy
  has_many :reviews, dependent: :destroy

  validates :name, :summary, :course, :kitchen, :photo, :description, presence: true
  validates :summary, length: { maximum: 30 }
  mount_uploader :photo, PhotoUploader

  accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
end

模型评论:

class Review < ActiveRecord::Base
  belongs_to :recipe

  validates :content, length: { minimum: 20 }
  validates :rating, presence: true
  validates_numericality_of :rating, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 5
  validates :content, presence: true
end

有人能看到问题吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

在RecipesController的show动作中创建Review Modal的新实例 - :

  

@review = Review.new

全部,我会工作。 :)

答案 1 :(得分:0)

你的RecipesController中有新方法吗?因为你在simpleform视图中使用@recipe。你需要

def new
@recipe = recipe.find(params[:recipe_id])
@review = Review.new(review_params)
end