简体   繁体   中英

how to write active record of rails for this query

Could anyone help me to write active record for this query..

SELECT c.name,c.profile_pic,cq.title FROM `coaches` as c join course_queries as cq on
    c.id = cq.coach_id WHERE cq.coach_id=1

class CourseQuery < ActiveRecord::Base belongs_to :student belongs_to :coach end

class Coach < ActiveRecord::Base has_many :course_queries end

You can try this way

Coach.joins(:course_queries).select("coaches.name,coaches.profile_pic,course_queries.title").where(:course_queries => {:coach_id => 1})

You can used eger loading with outer join as

@coaches = Coach.includes(:course_queries).where(:course_queries => {:coach_id => 1})

An select you data by

 @coaches.each do |coach|
    puts coach.name
    puts coach.course_queries.first.title   
   end

You can get all course queries by

  @coaches.each do |coach|
    puts coach.name
    coach.course_queries.each do |course_query|
       puts course_query.title 
     end
   end

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