I want to create a simple form to make new reviews for a recipe that has been posted in a cookbook. I render the review form on the recipe show page, but it keeps giving me the same error:
undefined method `model_name' for nil:NilClass
When I do not render the partial new review form at app/views/recipes/show.html.erb, but instead I create the file app/views/reviews/new.html.erb, only then the form works. I do not understand why the form is not working when I try to render it at show recipe page.
Here is my code:
Simple form for:
<%= 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 %>
Reviews controller:
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
Recipes controller:
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
Recipe show page:
<div class="review">
<%= render 'review/new' %>
<% @recipe.reviews.each do |review| %>
<%= review.content %>
<%= review.rating %>
<% end %>
</div>
Routes:
resources :recipes, only: [:index, :show] do
resources :reviews, only: [:create]
end
Models:
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
model review:
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
Can anyone see the problem? Thank you in advance!
Just create a new instance of Review model in the show action of RecipesController
@review = Review.new
That's all. It will work. :)