【问题标题】:Where are joins constructed in Rails?Rails 在哪里构建连接?
【发布时间】:2015-06-22 19:33:39
【问题描述】:

我遇到了 Rails 问题,我需要找到正在构建查询的连接部分的点。简而言之,问题在于不同版本的 Rails 对连接表使用不同的别名(可能是一个错误)。

我有两个使用单继承表的模型,我需要对此表进行查询,并引用第三个模型中的字段。我有兴趣了解如何构造以下查询的 "clients"."party_id"(表名)部分:

SELECT "clients".* 
FROM "clients" 
  LEFT OUTER JOIN "clients" "master_clients_clients" ON "master_clients_clients"."id" = "clients"."master_client_id" AND "master_clients_clients"."type" IN ('MasterClient') 
  LEFT OUTER JOIN "parties" ON "parties"."id" = "clients"."party_id" 
WHERE ("parties"."name" LIKE '%arty%')

我真的很难找到这一点,直到现在我还没有成功。因此,如果有任何关于这个方向的提示,将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4.2


    【解决方案1】:

    更新:

    来自File

    ActiveRecord::Associations::ClassMethods::JoinDependency 将关联分解为 baseassociationsjoins,它们进一步用于构造查询,如本文件中所述:

      # base is the base class on which operation is taking place.
      # associations is the list of associations which are joined using hash, symbol or array.
      # joins is the list of all string join commands and arel nodes.
      #
      #  Example :
      #
      #  class Physician < ActiveRecord::Base
      #    has_many :appointments
      #    has_many :patients, through: :appointments
      #  end
      #
      #  If I execute `@physician.patients.to_a` then
      #    base # => Physician
      #    associations # => []
      #    joins # =>  [#<Arel::Nodes::InnerJoin: ...]
      #
      #  However if I execute `Physician.joins(:appointments).to_a` then
      #    base # => Physician
      #    associations # => [:appointments]
      #    joins # =>  []
      #
    

    ActiveRecord 使用约定而不是配置。当你这样做时

    class Party < ActiveRecord::Base
       has_many :clients
    end
    

    假设您将有一个表名clients,它将party_id 字段作为表parties 的外键。

    您可以阅读有关这些约定的更多信息here

    【讨论】:

    • 我知道,我需要深入了解这些约定并了解它们是如何定义的。
    • @AndreiHorak:如果您想改写这些约定,可以前往here
    • 是单表继承,不需要不同的表名。我需要连接到使用表名来构建连接的地方。我需要看看这个操作使用了哪个别名。
    • @AndreiHorak:我相信这正在发生here
    • 这就是我在漫长的搜索中结束的地方,但仍然找不到相关的代码......
    【解决方案2】:

    也许在这里:activerecord/lib/active_record/relation/query_methods.rb 和线 L428More...

    【讨论】:

    • 我认为只有当您使用.joins 明确执行查询时才会执行。
    • 按照那个方法,也许它会引导你找到答案。好运。关注这个问题。
    猜你喜欢
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多