限制模型操作中的记录

时间:2010-12-28 21:30:56

标签: ruby-on-rails ruby limit

如何使用以下代码将我输出的记录数限制为仅3条记录:

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文件

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

更新:

我正在使用Rails 2.3.9

2 个答案:

答案 0 :(得分:6)

Rails 3:

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

Rails&lt; 3:

由于commentsArrayComment个对象,因此您只需slice

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

答案 1 :(得分:1)

comments中的任何workouts_on_which_i_commented,可以是Comment.all(:order => 'created_at DESC', :limit => 3)

也有一些花哨的rails 3语法,但这对两者都有好处。

或者,如果此方法在模型中,您可以执行comments(:order => 'created_at DESC', :limit => 3)而不是我的第一句中所描述的内容。