Rails 3中的分页和操作列表

时间:2011-06-01 23:15:20

标签: ruby-on-rails ruby-on-rails-3

我需要帮助在Rails中创建和分页列表。我有三个班级:

class User < ActiveRecord::Base
  has_many :rankings, :dependent => :destroy
  #...
  # has id, name, email, etc. 
end

class Ranking < ActiveRecord::Base
  belongs_to :essay
  belongs_to :user
  #...
  #has comment, score, essay_id, user_id
end

class Essay < ActiveRecord::Base
  has_many :rankings, :dependent => :destroy
  #...
  #has id, body, author, etc.
end

“排名”类会在每篇文章的评论中创建,然后相应地设置essay_iduser_id,以便我们知道谁在哪篇文章中排名。

现在,在应用程序的主页上,我想显示用户尚未排名的所有文章的分页列表。我想列出所有current_user尚未倾斜的文章的列表。对于所有的文章,我简单地做@essays = Essay.paginate(:page => params[:page]),但我想要这些的特定子集。我是否需要创建一系列未经批准的论文?

1 个答案:

答案 0 :(得分:0)

这是一个建议,不使用连接。

首先获取用户排名的所有文章

essay_ids = User.first.essay_ids

然后获取所有不包含这些ID的文章;)

@essays = Essay.where('id NOT IN (?)', essay_ids + [0])

我喜欢添加额外的0,因此空数组不会搞砸查询。

你可以在Essay的范围内种植这个

scope :not_ranked_by_user, lambda {|user| where('id NOT IN (?)', user.essay_ids + [0]) }