简体   繁体   中英

Joining two ActiveRecord associations on common attribute

Let's say I have a User model. User has 2 has_many associations, that is User has many pencils and has many cars. Cars and Pencils table has same attribute, :date, and separate such as :speed(car) and :length(pencil). I want to join a user's pencils and cars on their common attribute, :date, so that I have an array/relation [:date, :speed, :length]. How do I achieve that, I tried joins and merge but they were no use.

Many more efficient options exist, but here is one possible approach:

class User < ActiveRecord::Base
  def get_merged_array
    dates = (cars.map(&:date) & pencils.map(&:date))
    results = []
    dates.each do |date|
      cars.where(date: date).each do |car| 
        pencils.where(date: date).each do |pencil|
          results << [date, car.speed, pencil.length]
        end
      end
    end
    results
  end
end

I'd definitely recommend getting this into a query rather than a loop, for efficiency's sake. I think this will work:

Car.joins(:user => :pencils).where("pencils.date = cars.date")

And if you want to reduce it to the array immediately:

Car.joins(:user => :pencils).where("pencils.date = cars.date").pluck("cars.date", "cars.speed", "pencils.length")

If you need to include matches where date is nil , you might need to add:

Car.joins(:user => :pencils).where("(pencils.date = cars.date) OR (pencils.date IS NULL AND cars.date IS NULL)")

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