我有以下型號用聯合在arel中重寫複雜的查詢?
class Courier < ActiveRecord::Base
has_many :coverages
end
class Coverage < ActiveRecord::Base
belongs_to :courier
belongs_to :country_code
end
class CountryCode < ActiveRecord::Base
end
,然後我有以下查詢:
# could i translate this into cleaner arel?
result = Courier.find_by_sql(<<SQL
select * from
(
select cc.*, cv.rate from couriers cc, coverages cv
where cv.country_code_id=#{country.id} and cv.courier_id=cc.id
union
select cc.*, cv.rate from couriers cc, coverages cv
where cv.country_code_id is null
and cv.courier_id=cc.id
and cv.courier_id not in (select courier_id from coverages where country_code_id=#{country.id})
) as foo order by rate asc
SQL
)
總之:我正在尋找具有針對特定國家代碼或覆蓋所有快遞用空白的國家代碼覆蓋(後備)。
該查詢的工作原理,但我想知道是否有更好的方法來寫它?
我有一個類似的問題:http://stackoverflow.com/questions/4522746/how-would-i-join-to-a-subselect-a-scope-using-rails-3-and-arel – 2011-01-06 00:18:34