将Mysql代码转换为rails活动记录查询

时间:2017-03-24 06:47:34

标签: mysql ruby-on-rails activerecord ruby-on-rails-3.2

需要帮助将以下mysql查询转换为活动记录查询。

    SELECT ad_trek_participant.id, ad_registration_data.id, ad_registration_data.email, ad_registration_data.first_name,ad_registration_data.last_name, ad_trek_participant.status, ad_trek_participant.payment_status, COUNT( * ) AS occurrences
FROM ad_trek_participant
INNER JOIN ad_registration_data ON ad_trek_participant.Registration_Data_Id = ad_registration_data.id
WHERE ad_trek_participant.status = '2'
AND ad_trek_participant.payment_status = '2'
GROUP BY ad_trek_participant.Email_Id
HAVING COUNT( * ) >=5
LIMIT 0 , 1000

模型之间的关系为has_onebelongs_to

ad_registration_data has_one :participation, foreign_key: "registration_data_id"

ad_trek_participant belongs_to :registration_data, foreign_key: "Registration_Data_Id"

1 个答案:

答案 0 :(得分:0)

以下查询对我有用。

@participations = Participation.joins(:registration_data)
.where(payment_status:2,status:2)
.group("ad_registration_data.email")
.having("count(ad_registration_data.email)>=5")
.count('ad_registration_data.email')