lundi 28 mars 2016

Add comments to posts = undefined local variable or method `post' for

Hi there I have an error like this undefined local variable or method 'post' for #<#<Class:0x007ffc40469ad0>:0x007ffc40461088>

I don't understand because I create a partial in post which names _comments.html.erb

<p class="text-center">Poster un commentaire</p>
      <%= simple_form_for [post, post.comments.new] do |f| %>
        <%= f.error_notification %>
        <%= f.input :content, label: "Commentaire"%>
        <%= f.submit "Envoyer", class: "btn btn-primary" %>
      <% end %>

and it render like that <% render 'comments' %>

The undefined method is in this line <%= simple_form_for [post, post.comments.new] do |f| %>

the model post is has_many :comments, dependent: :destroy

the model post is has_many :comments, dependent: :destroy

the model comment is belongs_to :user belongs_to :post

The route is resources :posts do resources :categories resources :comments end

Comments controller is

class CommentsController < ApplicationController

before_action :set_post

def create
  @comment = @post.comments.build(comment_params)
  @comment.user_id = current_user.id

  if @comment.save
    flash[:success] = "You commented the hell out of that post!"
    redirect_to :back
  else
    flash[:alert] = "There is a problem with your comment"
    render root_path
  end
end

def destroy
  @comment = @post.comments.find(params[:id])

  @comment.destroy
  flash[:success] = "Comment deleted :("
  redirect_to root_path
end

private

def set_post
  @post = Post.find(params[:post_id])
end

def comment_params
  params.require(:comment).permit(:content, :post_id, :user_id)
end
end

Thank you so much for your help.

Aucun commentaire:

Enregistrer un commentaire