ruby-on-rails – 限制模型操作中的记录

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 限制模型操作中的记录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用以下代码将我输出的记录数限制为仅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

解决方法

Rails 3:

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

Rails< 3: 由于comments是一个Comment对象数组,因此您可以简单地对其进行切片:

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

猜你在找的Ruby相关文章