なんとなく日々徒然と

2つ以上のthrough

モデルで以下のABCDというクラスがあって、それぞれに親子関係がある場合。

A→B→C→D

かなり適当に書くとこうやって取れる。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class User_1 < ActiveRecord::Base
 has_many user_2
 has_many user_3, through: user_2
 has_many user_4, through: user_3
end

class User_2 < ActiveRecord::Base
 belongs_to user_1
 has_many user_3
end

class User_3 < ActiveRecord::Base
 belongs_to user_2
 has_many user_4
end

class User_4 < ActiveRecord::Base
 belongs_to user_3
end

User_1.user_4.first.class # => User_4

ちょっと感動したけど、普通にみんな使ってるのだろうか。

しかし、言いたいことは伝わると思うのだが、
コード適当すぎかも(–;)

Tags:

ぐぅかわ 全モデルから特定の列を持つモデルを抽出

comments powered by Disqus