Rails Joins and include columns from joins table

后端 未结 5 1194
小鲜肉
小鲜肉 2020-12-13 05:01

I don\'t understand how to get the columns I want from rails. I have two models - A User and a Profile. A User :has_many Profile (because users can revert back to an earlier

5条回答
  •  庸人自扰
    2020-12-13 05:14

    After reading these tips I got the joins to all be loaded in one query by reading 3 ways to do eager loading (preloading) in Rails 3 & 4.

    I'm using Rails 4 and this worked like a charm for me:

    refs = Referral.joins(:job)
              .joins(:referee)
              .joins(:referrer)
              .where("jobs.poster_id= ?", user.contact_id)
              .order(created_at: :desc) 
              .eager_load(:job, :referee, :referrer)
    

    Here were my other attempts.

    #first attempt
    #refs = Referral.joins(:job)
    #          .where("jobs.poster_id= ?", user.contact_id)
    #          .select("referrals.*, jobs.*")
    # works, but each column needs to be explicitly referenced to be used later.
    # also there are conflicts for columns with the same name like id
    
    #second attempt
    #refs = ActiveRecord::Base.connection.exec_query("SELECT jobs.id AS job_id, jobs.*, referrals.id as referral_id, referrals.* FROM referrals INNER JOIN jobs ON job_id = referrals.job_id WHERE (jobs.poster_id=#{user.contact_id});")
    # this worked OK, but returned back a funky object, plus the column name
    # conflict from the previous method remains an issue.
    
    
    #third attempt using a view + rails_db_views
    #refs = JobReferral.where(:poster_id => user.contact_id)
    # this worked well. Unfortunately I couldn't use the SQL statement from above
    # instead of jobs.* I had to explicitly alias and name each column.
    # Additionally it brought back a ton of duplicate data that I was putting
    # into an array when really it is nice to work with ActiveRecord objects.
    
    #eager_load
    #refs = Referral.joins(:job)
    #          .where("jobs.poster_id= ?", user.contact_id)
    #          .eager_load(:job)
    # this was my base attempt that worked before I added in two more joins :)
    

提交回复
热议问题