我想创建一个简单的表单来对食谱中发布的食谱进行新的评论。我在食谱显示页面上呈现评论表单,但它一直给我同样的错误:
- undefined method `model_name' for nil: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条答案
按热度按时间fjaof16o1#
只需在RecipesController的show操作中创建Review模型的新示例
@review =Review.new
就这样,它会起作用的。:)
bq9c1y662#
你在你的RecipesController里有新的方法吗?因为你在simpleform视图中使用了@recipe。你需要