Shows the user who last commented on the message (Rails)?

I have a Post model:

class Post < ActiveRecord::Base attr_accessible :title, :content, :tag_names belongs_to :user has_many :comments, :dependent => :destroy end belongs_to :post, :counter_cache => true belongs_to :user end 

a User Model:

 class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :avatar, :subscribed_tag_names has_many :posts, :dependent => :destroy has_many :comments, :dependent => :destroy end 

and comment model:

 class Comment < ActiveRecord::Base attr_accessible :content, :user_id belongs_to :post, :counter_cache => true belongs_to :user end 

This is how I show the user who created the message in the index.html.erb view:

  <% @posts.each do |post| %> <div id="post-<%= post.id %>" class="post"> <h3 class="post-title"><%= link_to post.title, post %></h3> <div class="post-author"> <span class="profile-picture"> <%= image_tag post.user.avatar.url(:thumb) %> </span> <span class="post-author-name"> <strong><%= link_to post.user.username, post.user %></strong> </span> </div> 

(etc....)

How to display the user who last commented on the message (as you can see in StackOverflow and in different forums)?

0
source share
3 answers

The previous answer only works when your post has some comments. When there are no comments, you will receive an error message, as you have already noted.

You can solve this by simply testing these comments before trying to deduce it:

 <% @posts.each do |post| %> ... <% if post.comments.empty? %> Nobody has commented yet <% else %> <%= post.comments.last.user.email %> <% end %> <% end %> 
+1
source
 <% comment = post.comments.order(:created_at).reverse_order.first %> <%= comment.user.email if comment %> 

This does the following:

it receives all the comments on the message, sorted by the created_at field in reverse order (i.e. the highest value above). From this, he selects the first value, i.e. The newest comment. From this comment you get user .

Customizing the order is not optional since databases can return items in random order if they are not explicitly specified. You will be more likely to observe random order in Postgres or Oracle than in MySQL or SQLite, because they store records. However, they will all return random orders of elements, at least sometimes if the order is not specified.

+2
source
 <% @posts.each do |post| %> ... <%= post.comments.last.user.email %> <% end %> 
+1
source

Source: https://habr.com/ru/post/1402346/


All Articles