LoginSignup
38
39

More than 5 years have passed since last update.

Rails (ActiveRecord) で scope と joins する方法

Last updated at Posted at 2014-04-10

答え

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 []>

参考文献

38
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
39