获取 has_many 和 belongs_to 生成的 SQL
有的时候我们想要分析 Rails ORM 生成的 SQL
has_many 关系 比较容易获取
belongs_to 关系 稍微麻烦一些
关键点在于 ActiveRecord::Relation#to_sql
https://github.com/rails/rails/blob/v3.2.17/activerecord/lib/active_record/relation.rb#L458
class Customter
has_many :orders
end
class Order
belongs_to :customter
end
Customter.first.orders.to_sql
# => SELECT `orders`.* FROM `orders` WHERE `orders`.`customer_id` = 136
# => BTW 136 is customer_id
Order.first.association(:customer).association_scope.to_sql
# => SELECT `customers`.* FROM `customers` WHERE `customers`.`id` = 136
# => BTW 136 is customer_id
Customter.first.orders.proxy_association.association_scope.class
# => ActiveRecord::Relation
Order.first.association(:customer).association_scope.class
# => ActiveRecord::Relation
关于更多技术实现细节,可以研究 ActiveRecord::Associations#association
https://github.com/rails/rails/blob/v3.2.17/activerecord/lib/active_record/associations.rb#L155