224
183

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-06-28

テーブル構成

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で同じおじいちゃんを持つ曾孫とかで絞り込めるのです。

224
183
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
224
183

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?