简体   繁体   中英

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?

Assuming you have the association :cars setup

People.joins(:cars).where("persons.state=cars.state AND persons.state_id_number=cars.owner_id_number").all

Won't be exactly the same, but it should be close

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM