开发者

Limiting records in a model action

How do I limit the number of records that I am outputting with the following code to only 3 records:

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 开发者_JAVA技巧|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'm using Rails 2.3.9


Rails 3:

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

Rails < 3:

Since comments is an Array of Comment objects, you can simply slice it:

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


whatever comments is in your workouts_on_which_i_commented, could be Comment.all(:order => 'created_at DESC', :limit => 3)

There is some fancy rails 3 syntax too, but this is good for either.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜