如何为此查询编写rails的活动记录

时间:2015-10-05 07:29:39

标签: ruby-on-rails activerecord

有没有人可以帮我写这个查询的活动记录..

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

1 个答案:

答案 0 :(得分:0)

你可以试试这种方式

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

您可以将外部联接的eger加载用作

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

选择您的数据
 @coaches.each do |coach|
    puts coach.name
    puts coach.course_queries.first.title   
   end

您可以通过

获取所有课程查询
  @coaches.each do |coach|
    puts coach.name
    coach.course_queries.each do |course_query|
       puts course_query.title 
     end
   end