0

在我的 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 方法调用链?或者也许是一种让 pluck 返回一个ActiveRecord::Relation而不是一个数组的方法?

4

1 回答 1

3

试试这个:

@authors = Book.limit(10).offset(params[:page]*10).all_authors
# => ["first pair of authors", "second pair of authors", ...]

您只需要pluck在链的末尾调用该方法。

否则,您可以使用selectwhich 只会从数据库中返回指定的列:

@authors = Book.select(:author).limit(10).offset(params[:page]*10)
# => [#<Book author: "first pair of authors">, #<Book author: "second pair of authors">, ...]
于 2013-05-22T13:51:17.603 回答