Restricting records in model action

How to limit the number of entries that I output using the following code to just 3 entries:

User.rb

  def workouts_on_which_i_commented
    comments.map{|x|x.workout}.uniq
  end

  def comment_stream
   workouts_on_which_i_commented.map do |w|
     w.comments
   end.flatten.sort{|x,y| y.created_at <=> x.created_at}
 end

html.erb file

<% current_user.comment_stream.each do |comment| %>
    ...
<% end %>

UPDATE:

I am using Rails 2.3.9

+3
source share
2 answers

Rails 3:

def workouts_on_which_i_commented
  comments.limit(3).map{|x|x.workout}.uniq
end

Rails <3:

Since it commentsis an Arrayobject Comment, you can just sliceit:

def workouts_on_which_i_commented
  comments[0..2].map{|x|x.workout}.uniq
end
+6
source

everything commentsin your workouts_on_which_i_commentedmaybeComment.all(:order => 'created_at DESC', :limit => 3)

There are also several fancy rails 3 syntax, but that is good for.

Or, if this method is in the model, you can simply do comments(:order => 'created_at DESC', :limit => 3)instead of what was described in my first sentence.

+1
source

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


All Articles