In my Rails app, I've written a method that generates an array of unique names from a set of records in the database:
class Book < ActiveRecord::Base
attr_accessible :title, :author
def self.all_authors
self.uniq.pluck(:author)
end
end
This method works as expected, but this application may end up having a large number of authors so now I want to paginate this query in the controller.
class AuthorsController < ApplicationController
def index
@authors = Book.all_authors.limit(10).offset(params[:page]*10)
end
end
Obviously, this doesn't work because pluck(:authors)
returns an array and not an ActiveRecord::Relation
. Is there an alternative to pluck
that would allow me to use Arel method call chains? Or perhaps a way to make pluck return an ActiveRecord::Relation
instead of an array?
Try this:
@authors = Book.limit(10).offset(params[:page]*10).all_authors
# => ["first pair of authors", "second pair of authors", ...]
You just need to call the pluck
method at the end of the chain.
Otherwise you can use select
which will only return the specified columns from the database:
@authors = Book.select(:author).limit(10).offset(params[:page]*10)
# => [#<Book author: "first pair of authors">, #<Book author: "second pair of authors">, ...]