【问题标题】:How can I check associated attributes in Rails?如何检查 Rails 中的关联属性?
【发布时间】:2015-08-11 14:41:05
【问题描述】:

我有以下关系

User has_many Clients 通过 ClientMemberships

Client has_many Projects

Project belongs_to Client

给定一个特定的用户。为具有特定项目 ID 的用户查找所有客户的最佳方法是什么。

我不想遍历所有项目并用 ruby​​ 检查每个项目,而不是使用一些 SQL 来完成这项工作,同时考虑到预加载。

【问题讨论】:

    标签: ruby-on-rails activerecord eager-loading


    【解决方案1】:
    @user.clients.joins(:projects).where("projects.id = ?", your_project_id)
    

    【讨论】:

    • 既然我确定了我的答案,我猜你的答案是第一个:)
    【解决方案2】:
    class User
      def clients_for_project_id(project_id)
        clients.joins(:projects).where(projects: { id: project_id })
      end
    end
    

    【讨论】:

    • 另一方面,你有一种写“where”语句的非硬编码方式:)
    • 虽然,据我在这里看到apidock.com/rails/ActiveRecord/QueryMethods/where(例如:User.joins(:posts).where({ posts: { published: true } })),你应该有“where (projects:" 而不是 "where(project:".
    【解决方案3】:

    这很简单,使用joins 对另一个表执行条件,使用inculdes 进行预加载。

    user.clients
      .joins(:projects)
      .includes(:projects)
      .where(projects: { id: project_id })
    

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多