0

假设我想做

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

提示:不同州的人可以有相同的state_id_number,但在一个州内是独一无二的。

我可以

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")

获取记录列表。

但是我可以使用该find(:all, :conditions => {格式来做同样的事情吗?

4

2 回答 2

1

假设您有关联 :cars 设置

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

不会完全一样,但应该很接近

于 2012-10-12T22:03:03.740 回答
0
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)
于 2012-10-12T22:25:52.920 回答