Sql Rails activerecord内部连接自定义对象
我有以下课程:Sql Rails activerecord内部连接自定义对象,sql,ruby,ruby-on-rails-3,activerecord,Sql,Ruby,Ruby On Rails 3,Activerecord,我有以下课程: class Want < ActiveRecord::Base has_many :cached_buy_offers, dependent: :destroy end class CachedBuyOffer < ActiveRecord::Base belongs_to :want end 这和预期的一样。 我想生成以下sql: select * from wants inner join (select cached_buy_offers.want_
class Want < ActiveRecord::Base
has_many :cached_buy_offers, dependent: :destroy
end
class CachedBuyOffer < ActiveRecord::Base
belongs_to :want
end
这和预期的一样。
我想生成以下sql:
select * from wants
inner join
(select cached_buy_offers.want_id, max(buy_offer_cents) as max_buy_offer, count(cached_buy_offers.want_id) as buy_offer_count
from cached_buy_offers
where cached_buy_offers.want_id in (1,2,3,4)
group by cached_buy_offers.want_id
order by max_buy_offer) as cached_buy_offers
on cached_buy_offers.want_id = wants.id
可以使用以下命令生成内部sql查询:
ids = [1,2,3,4]
CachedBuyOffer.select('cached_buy_offers.want_id, max(buy_offer_cents) as max_buy_offer, count(cached_buy_offers.want_id) as buy_offer_count').where('cached_buy_offers.want_id in (?)',ids).group('cached_buy_offers.want_id').order('max_buy_offer')
但当我尝试这样做时:
Want.joins(CachedBuyOffer.select ..... the above activerecord inner query)
抛出错误运行时错误:未知类:CachedBuyOffer
如何生成所需的sql?
.joins
将关联键作为参数,例如Want.joins(:cached\u buy\u offer)
。您可以将查询从中链接出来 您可以使用Arel.sql
ids = [1,2,3,4]
cached_buy_offer_subquery = CachedBuyOffer
.select('cached_buy_offers.want_id,
max(buy_offer_cents) as max_buy_offer,
count(cached_buy_offers.want_id) as buy_offer_count')
.where('cached_buy_offers.want_id in (?)',ids)
.group('cached_buy_offers.want_id')
.order('max_buy_offer').to_sql
Want.joins("INNER JOIN (#{Arel.sql(cached_buy_offer_subquery)}) cached_buy_offers ON cached_buy_offers.want_id = wants.id")
我在rails控制台中尝试了这一点,其中也定义了CachedBuyOffer。我还能够独立执行activerecord内部查询。那么您是否尝试过,
Want.joins(:cached_by_offer)。选择(…)
?
ids = [1,2,3,4]
cached_buy_offer_subquery = CachedBuyOffer
.select('cached_buy_offers.want_id,
max(buy_offer_cents) as max_buy_offer,
count(cached_buy_offers.want_id) as buy_offer_count')
.where('cached_buy_offers.want_id in (?)',ids)
.group('cached_buy_offers.want_id')
.order('max_buy_offer').to_sql
Want.joins("INNER JOIN (#{Arel.sql(cached_buy_offer_subquery)}) cached_buy_offers ON cached_buy_offers.want_id = wants.id")