1

I'd like to convert the following statements (that work) into something "more elegant" using 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

Models look like

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'

Basically I want to count the number of different Places of a collection of Trips.

Any suggestion will be much appreciated !

Update: Best I've come up so far still looks a bit ugly to me (it fires up 3 SQL requests):

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

I could also do a simple

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

But that defeat my purpose of using ActiveRecord up to its potential.

Any simpler elegant solution in ActiveRecords?

2
  • hey you need to learn active record in rails first. that will help you a lot guides.rubyonrails.org/association_basics.html
    – Nitin Jain
    Feb 10, 2014 at 16:47
  • Hi @NitinJ, I do indeed use ActiveRecord for everything else but having trouble with that particular request. I've updated my question with what I've come up with so far in ActiveRecord.
    – Sly
    Feb 11, 2014 at 5:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.