Search code examples
mysqlactiverecordruby-on-rails-3.1

ActiveRecord find with composite join


Suppose I want to do

SELECT persons.name, cars.registration FROM persons, cars 
   WHERE persons.state=cars.state AND persons.state_id_number=cars.owner_id_number ;

Hint: people in different states can have the same state_id_number but it is unique within a state.

I can do

People.find_by_sql("SELECT persons.name, cars.registration FROM persons, cars
   WHERE persons.state=cars.state AND persons.state_id_number=cars.owner_id_number")

to get a list of records.

But can I use the find(:all, :conditions => { format to do the same thing?


Solution

  • class Person < ActiveRecord::Base
      has_many :cars,
          :foreign_key => "owner_id_number",
          :primary_key => "state_id_number",
          :conditions => "persons.state = cars.state"
    end
    
    class Car < ActiveRecord::Base
      belongs_to :person,
          :foreign_key => "owner_id_number",
          :primary_key => "state_id_number",
          :conditions => "persons.state = cars.state"
    end
    
    Person.includes(:cars)