在我的Rails应用程序中,我编写了一个方法,从数据库中的一组记录生成一个唯一名称数组:
class Book < ActiveRecord::Base
attr_accessible :title, :author
def self.all_authors
self.uniq.pluck(:author)
end
end
这个方法按预期工作,但是这个应用程序最终可能有大量的作者,所以现在我想在控制器中对这个查询进行分页。
class AuthorsController < ApplicationController
def index
@authors = Book.all_authors.limit(10).offset(params[:page]*10)
end
end
显然,这不起作用,因为pluck(:authors)
返回一个数组而不是ActiveRecord::Relation
。是否有一个替代pluck
,将允许我使用Arel方法调用链?或者一种方法,使拔返回一个ActiveRecord::Relation
而不是一个数组?
试试这个:
@authors = Book.limit(10).offset(params[:page]*10).all_authors
# => ["first pair of authors", "second pair of authors", ...]
您只需要在链的末尾调用pluck
方法。
否则,您可以使用select
,它将只从数据库返回指定的列:
@authors = Book.select(:author).limit(10).offset(params[:page]*10)
# => [#<Book author: "first pair of authors">, #<Book author: "second pair of authors">, ...]