在Rails中构建的连接在哪里?

时间:2015-04-16 11:55:31

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

我遇到了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%')

我真的很难找到这一点,直到现在我还没有成功。所以,我会很感激这方面的任何提示。

2 个答案:

答案 0 :(得分:0)

更新:

来自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

答案 1 :(得分:0)

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