4
3

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.

ネストが深い joins の表記

Last updated at Posted at 2016-02-10
class User < ActiveRecord::Base
  has_many :assignments
  has_many :projects, through: :assignments
end

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :assignments
  has_many :users, through: :assignments
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

captured.png

というモデルがある。

ここで、user 指定(id = 1)で task を取り出すには、以下のようになるのだけど、

Task.joins(project: {assignments: :user}).where(users: {id: 1})

「joins の中って、単数?複数?どっち?」みたいなことで悩んでしまった。

もちろん、

tasks(多)- project(1)- assignments(多)- user(1) 

ということ。

where については、テーブル名指定なので users。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?