LoginSignup
183

More than 5 years have passed since last update.

posted at

updated at

Railsでjoinsを多段ネストする方法(親から曾孫まで)

テーブル構成

class Foo < ActiveRecord::Base
  has_many :bars
end

class Bar < ActiveRecord:Base
  belongs_to :foo
  has_many :bazs
end

class Baz < ActiveRecord:Base
  belogs_to :bar
  has_many :hoges
end

class Hoge < ActiveRecord:Base
  belogs_to :baz
end

joins

親から辿る場合には

Foo.joins({:bars => {:bazs => :hoges}})

となる。has_manyでのテーブル指定は複数形。

曾孫から辿る場合には

Hoge.joins({:baz => {:bar => :foo}})

となる。belogs_toでのテーブル指定は単数形

where

whereで検索する場合には

Hoge.joins({:baz => {:bar => :foo}}).where('foos.id = 1)

となる。

Hoge.joins({:baz => {:bar => :foo}}).where(:foos => {:id => 1})

という書き方もできる。

whereの中のテーブル指定は複数形。

何が嬉しいの?

active adminのfilterで同じおじいちゃんを持つ曾孫とかで絞り込めるのです。

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
What you can do with signing up
183