[英]ActiveRecord find with composite join
假设我想做
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 => {
format做同样的事情吗?
假设您具有关联:汽车设置
People.joins(:cars).where("persons.state=cars.state AND persons.state_id_number=cars.owner_id_number").all
不会完全一样,但是应该接近
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.