2014-09-15 4 views
0

다음 연관이 있습니다.레일 4, 중첩 된 연관 검색

class Farm < ActiveRecord::Base 
    has_many :crops 
end 

class Crop < ActiveRecord::Base 
    belongs_to :farm 
    has_many :seed_batches 
end 

class SeedBatch < ActiveRecord::Base 
    belongs_to :crop 
    has_many :tasks, through: :task_batches 
end 

class Task < ActiveRecord::Base 
    has_many :seed_batches, through: :task_batches 
end 

class TaskBatch < ActiveRecord::Base 
    belongs_to :task 
    belongs_to :seed_batch 
end 

본질적으로 농장에는 많은 작물이 있습니다. 각 작물에는 많은 종자 배치가 있습니다. 각 시드 배치에는 많은 작업이 있습니다.

내 질문은 다음과 같습니다. 모든 작업에 팜의 ID를 알리는 방법은 무엇입니까?

.where() 검색을 여러 방법으로 시도했지만 모두 오류가 발생했습니다. 아무도 나를 계몽 수 있습니까?

답변

0

당신은 자르기 및 농장에 대한 has_many :tasks을 정의 할 수 있어야한다

Farm.find(1).crops.each(&:seed_batches).collect(&:tasks) 
+0

감사합니다 모든 작업에 액세스 할 수 있어야합니다! 그것은 작동합니다! 와우. Task에서 생각하고있는 동안, 그들이 같은 농장에 속해 있는지 어떻게 알 수 있습니까? 그러나 나는 완전히 다른 방향에서 그것을 보지 못했습니다! 전망 ... 고마워! –

+0

문제 없음! 다행이야! –

0

을 시도해보십시오

class Farm < ActiveRecord::Base 
    has_many :crops 
    has_many :tasks, through: :crops 
end 

class Crop < ActiveRecord::Base 
    belongs_to :farm 
    has_many :seed_batches 
    has_many :tasks, through: :seed_batches 
end 

는 그런 다음 Farm.find(id).tasks