D
D
dexdev2013-12-09 22:31:17
ruby
dexdev, 2013-12-09 22:31:17

How do I display the name of the user who created the comment in Rails?

In general, there are users comments and there are posts, how to register associations between models in order to show on the posts who wrote the comment?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanKiLL, 2013-12-10
@AdilA

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
  has_many :comments, dependent: :destroy
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments, dependent: :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

class PostsController < ApplicationController
  def index
    @posts = Post.includes(:user, :comments).order('created_at DESC')
  end
end

<% @posts.each do |post| %>
  <%= link_to post.user.user_name, user_path(post.user) %> #кто написал пост
  <% post.comments.each do |comment| %> #проходимся по комментам
    <%= comment.user.user_name%> # кто написал коммент
  <% end %>
<% end %>

As someone so, if you need comments / explanations, ask.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question