繁体   English   中英

Rails的nil:NilClass简单形式未定义方法`model_name'

[英]Rails simple form undefined method `model_name' for nil:NilClass

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

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

谁能看到这个问题? 先感谢您!

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

@review =评论。新

就这样,我会工作。 :)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM