我有以下关联。
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()搜索,但都出现了错误。有人能启发我吗?
尝试
Farm.find(1).crops.each(&:seed_batches).collect(&:tasks)
您应该能够为Crop and Farm:定义has_many :tasks
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
访问所有任务