使用多个From in Rails Active Records转换SQL(相同的Model关联两次)

时间:2014-02-10 16:45:11

标签: sql ruby-on-rails ruby activerecord ruby-on-rails-4

我希望将以下陈述(有效)转换为更优雅的陈述#34;使用Active Records。

query = "SELECT COUNT (DISTINCT places.id) as total_places
     FROM trips, places
     WHERE trips.id in (?)
      AND (places.id = trips.from_place_id 
        OR places.id = trips.to_place_id)"
Place.find_by_sql([query, @trips.ids]).first.total_places

模型看起来像

class Trip < ActiveRecord::Base
    belongs_to :from_place, :class_name => 'Place'
    belongs_to :to_place,   :class_name => 'Place'

class Place < ActiveRecord::Base
has_many :from_place_trips, :class_name => 'Trip', :foreign_key => 'from_place_id'
has_many :to_place_trips,   :class_name => 'Trip', :foreign_key => 'to_place_id'

基本上我想计算一系列旅行的不同地方的数量。

任何建议都将不胜感激!

更新 到目前为止我遇到的最好看起来对我来说仍然有点难看(它引发了3个SQL请求):

Place.where('id IN (?) OR id IN (?)'
          , @trips.pluck(:from_place_id)
          , @trips.pluck(:to_place_id)).distinct.count

我也可以做一个简单的

( @trips.pluck(:from_place_id) | @trips.pluck(:to_place_id)).count 

但这使我无法使用ActiveRecord达到其潜力。

ActiveRecords中任何更简单优雅的解决方案?

0 个答案:

没有答案