関係を持っていないモデルの一覧を取得する
class CreateUserSections < ActiveRecord::Migration create_table "users", :force => true do |t| t.column :name, :string end def self.down drop_table :user_sections end end
と
class CreateUserSections < ActiveRecord::Migration def self.up create_table :user_sections do |t| t.column :user_id, :integer, :null=>false t.column :section_id, :integer, :null=>false end end def self.down drop_table :user_sections end end
というmigrationファイルのDBがあるとします。
モデルは以下のようになっています。
class User < ActiveRecord::Base has_one :user_section end
class UserSection < ActiveRecord::Base belongs_to :user belongs_to :section end
このほかにもSectionとかあるのですが、今回はとりあえず省略します。
そして、userの一覧を取得したいのですが、
user_sectionsに出てこないユーザの一覧を出すにはどうすればいいのでしょうか?
xibbarのやり方は配列を作ってから引き算をするというやりかたで
おそらく遅いやり方です。
unsectioned_users=User.find(:all)-UserSection.find(:all).map{|us|us.user}
この話を某chatで聞いてみたところ、id:yamaz氏と舞波氏が答えを出してくれました。
unsectioned_users=User.find(:all, :include =>[:user_section], :conditions=>['user_sections.user_id is null'])
これだとクエリ一発ですこぶる速そうです。eager loadingで取得したものをconditionsに
かけられるとは初めて知りました。