Я хотел бы иметь возможность отображать имя пользователя человека, который прокомментировал сообщение. У меня есть некоторые трудности с отображением этого. Как сейчас выглядит код, я получаю неопределенный метод `user' для nil:NilClass в представлении для строки: ‹%= @comment.user.name %>. Заранее еще раз спасибо.
Контроллер комментариев
class CommentsController < ApplicationController
before_filter :authenticate_user!
def new
@post = Post.find(params[:post_id])
@comment = Comment.new
end
def create
@post = Post.find_by_id(params[:post_id])
@comment = @post.comments.create(params.require(:comment).permit(:commenter, :body))
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render json: @comment, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
def show
@comment = Comment.new
end
private
def comment_params
params.require(:comments).permit(:commenter, :body)
end
end*
Просмотр/_комментарии
<%= div_for(comment) do %>
<p>
<strong>Posted <%= time_ago_in_words(comment.created_at) %> ago</strong></br>
<%= h(comment.body) %>
<%= @comment.user.name %>
<%= link_to 'Delete', [@post, comment], :method => :delete, :confirm => "Are you sure?" %>
</p>
<% end %>
Модель пользователя
has_many :comments
Модель комментариев
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end