我想创建一个简单的表单,以便为已发布在食谱中的食谱创建新的评论。我呈现的配方显示页面上的形式审查,但它不断给我同样的错误:Rails简单形式未定义的方法`model_name'为零:NilClass
未定义的方法`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
任何人都可以看到这个问题?先谢谢你!
你介意发布模型和RecipesController吗? –
我会发布它们 – Seifer
我相信你的问题在于** @ recipe = Recipe.find(params [:id])**没有找到相应的配方,然后返回nil。然后,在视图中,当你说**@recipe.reviews.each**时,它会抱怨你引用了一个无类的模型名称(Review)。 –