[英]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. 提示:不同州的人可以具有相同的
state_id_number
但在一个州内是唯一的。
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? 但是我可以使用
find(:all, :conditions => {
format做同样的事情吗?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.