限制模型操作中的记录

bga*_*oci 3 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

html.erb文件

<% current_user.comment_stream.each do |comment| %>
    ...
<% end %>
Run Code Online (Sandbox Code Playgroud)

更新:

我正在使用Rails 2.3.9

Jac*_*kin 6

Rails 3:

def workouts_on_which_i_commented
  comments.limit(3).map{|x|x.workout}.uniq
end
Run Code Online (Sandbox Code Playgroud)

Rails <3:

因为comments一个是ArrayComment对象,你可以简单地slice是:

def workouts_on_which_i_commented
  comments[0..2].map{|x|x.workout}.uniq
end
Run Code Online (Sandbox Code Playgroud)