答え
ActiveRecord::SpawnMethods#merge を使うらしい。
動作確認
前提
db/migrate/20140410025937_create_authors.rb
class CreateAuthors < ActiveRecord::Migration
def change
create_table :authors do |t|
t.string :name
t.timestamps
end
end
end
db/migrate/20140410030000_create_books.rb
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.integer :author_id
t.string :title
t.datetime :published_at
t.timestamps
end
end
end
app/models/author.rb
class Author < ActiveRecord::Base
has_many :books
end
app/models/book.rb
class Book < ActiveRecord::Base
belongs_to :author
scope :published, -> { where(arel_table[:published_at].not_eq(nil)) }
end
実行
$ bundle exec rails c
Loading development environment (Rails 4.0.3)
irb(main):001:0> Author.joins(:books).merge(Book.published)
Author Load (0.1ms) SELECT "authors".* FROM "authors" INNER JOIN "books" ON "books"."author_id" = "authors"."id" WHERE ("books"."published_at" IS NOT NULL)
=> #<ActiveRecord::Relation []>