在做项目的时候碰到这样一个问题,有两个模型:category和content,他们是多对多的关联,他们的关联模型是categoring
我要做的是根据某个特定的category来检索content,并对content分页。
Controller的代码:
- @category = Category.find(params[:id])
- content_ids = @category.categorings.collect{|categoring| categoring.content_id}
- #首先取出中间表里该模型的记录集合(数组)
- if !(content_ids == []) #然后判断该集合是否为空,如果为空则不做查询分页
- @contents = Content.paginate(:all,
- :conditions => "id IN (#{content_ids.join(',')})",
- :page => params[:page], :per_page => 2)
- #如果不为空则对关联表进行分页(利用will_paginate插件)
- end
然后就可以在views中利用进行分页了。