2014-03-19 83 views
-1
SELECT rs.id as rs_id, 
sum(rs.amount_per_month) as rs_am1, 
sum(rs.amount_per_month_per_sqft) as rs_am2, 
rs.from_date,rs.to_date,cc.charge_type as cc 
FROM lease_rent_rolls as lrr 
INNER JOIN leases as l ON lrr.lease_id = l.id 
INNER JOIN rents as r ON l.id = r.lease_id 
INNER JOIN rent_schedules as rs ON r.id = rs.rent_id 
INNER JOIN charge_codes as cc ON rs.charge_code_id = cc.id 
WHERE lrr.id = 449443 
AND DATE(NOW()) BETWEEN rs.from_date AND rs.to_date 
GROUP BY cc.charge_type 

我在模型中使用此SQL查詢中使用find_by_sql,但我應該得到這個同樣的結果在Ruby中加入WHERE條件在模型中沒有的幫助SQL。如何寫的Ruby這個sql查詢加入查詢(Ruby on Rails的)

+2

您能否向我們展示您的模型,包括它們之間的關聯? – BroiSatse

+0

請分享您的模特協會,然後它會更有幫助。 – uma

回答

0

事情是這樣的:

@goods =Good.joins(:user).where("name like ?", "%#{@searched_good}%").where("category_id = ?", params[:category]).where("postal_code == ?", @searched_good_postal_code) 

有: - CATEGORY_ID和名稱,是屬於好陣列 - POSTAL_CODE屬於用戶陣列

+0

感謝帖子,但是m需要加入多個表格。 – Janu

1

如果你提供的關聯那麼這將是更有利於提供解。現在

,我正在考慮:

LeaseRentRoll有一個或多個租賃。

租賃有很多租金。

租有很多rent_schedules。

和RentSchedule有很多charge_codes。

如果LeaseRentRoll有一個租賃:

LeaseRentRoll.where(:id => 449443).first.lease.joins(:rents => [:rent_schedules => charge_codes]).select("rent_schedules.id as rs_id, sum(rent_schedules.amount_per_month) as rs_am1, sum(rent_schedules.amount_per_month_per_sqft) as rs_am2, 

rent_schedules.from_date,rent_schedules.to_date,charge_codes.charge_type爲CC「)

如果LeaseRentRoll有許多租賃:

LeaseRentRoll.where(:id => 449443).first.leases.joins(:rents => [:rent_schedules => charge_codes]).select("rent_schedules.id as rs_id, sum(rent_schedules.amount_per_month) as rs_am1, sum(rent_schedules.amount_per_month_per_sqft) as rs_am2, rent_schedules.from_date,rent_schedules.to_date,charge_codes.charge_type as cc") 

請看看附圖,這將有助於更多地瞭解上述查詢。

enter image description here

1
RentSchedule.joins([{:rent => {:lease => :lease_rent_rolls}}, :charge_code]).where("lease_rent_rolls.id = #{lease_rr.id} 
and rent_schedules.from_date < '#{Date.today.strftime("%Y-%m-%d %H:%M:%s")}' 
and rent_schedules.to_date > '#{Date.today.strftime("%Y-%m-%d %H:%M%s")}'").group("charge_codes.charge_type") 

得到了結果這個Query.Thanks大家!

+0

隨時接受你自己的答案。 – Pavan