【问题标题】:Rails—Get all records with same grandparentRails - 获取具有相同祖父母的所有记录
【发布时间】:2016-12-11 22:33:03
【问题描述】:

我有三个模型,Organisation 有很多 User 有很多 Project

如何查询属于同一组织的所有Project

目前我有Project.joins(user: [:organisation]),但这只是获取所有Project 并将它们按User 分组。我不确定如何指定Organisation id。

【问题讨论】:

    标签: ruby-on-rails scope ruby-on-rails-5


    【解决方案1】:

    假设您有一个名为 organisation 的局部变量,其中填充了您感兴趣的组织,您可以在查询中添加 where

    Project.joins(user: [:organisation]).where('organisations.id = ?', organisation.id)
    

    但使用您已建立的关联(或创建新的关联)可能更有用

    class User < ActiveRecord::Base
      has_many :projects
    end
    
    class Organisation < ActiveRecord::Base
      belongs_to :user
      has_many :projects, through: :user
    end
    

    然后您可以向您的组织询问其项目:

    organisation = Organisation.find(params[:id])
    organisation.projects
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2019-09-14
      相关资源
      最近更新 更多