3

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

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

当我不在app/views/recipes/show.html.erb呈现部分新评论表单,而是创建文件app/views/reviews/new.html.erb时,只有这样表单才有效。我不明白为什么当我尝试在显示配方页面呈现表单时表单不起作用。

这是我的代码:

简单的形式:

<%= 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

任何人都可以看到问题吗?先感谢您!

4

2 回答 2

4

只需在 RecipesController 的显示操作中创建 Review Modal 的新实例 -:

@review = Review.new

就是这样,我会工作。:)

于 2016-05-15T17:55:20.523 回答
0

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

def new
@recipe = recipe.find(params[:recipe_id])
@review = Review.new(review_params)
end
于 2016-05-15T11:15:21.007 回答