【问题标题】:Rails 4, nested association searchRails 4,嵌套关联搜索
【发布时间】:2014-09-15 09:31:44
【问题描述】:

我有以下关联。

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() 搜索,但都出现了错误。哪位大神可以赐教一下?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations where


    【解决方案1】:

    试试

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

    【讨论】:

    • 谢谢!有用!哇。一直以来我一直在思考任务,我如何确定它们是否属于同一个农场。但我完全没有从相反的角度看到它!观点...谢谢!
    【解决方案2】:

    您应该能够为 Crop 和 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访问所有任务

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多