2011-10-13 51 views
1

我有一个Product和Creator表,我也有一个名为CreatorProduct的表,它将创建者与产品结合在一起。产品可以有许多创造者,创造者可以有许多产品。我想要做的是找到有创作者的产品,有些产品可能没有创作者。Rails和sql:重写find_by_sql

我已经编写了下面的代码,但是如何以更友好的方式编写它?这适用于我在Rails控制台,但是当我把它放在我的代码,我得到 未定义的方法'包括为#

Product.find_by_sql("select * from Products where id in (select product_id from Creator_Products intersect select id from Products)") 

谢谢!

回答

0

我可能只是使用查找功能,并使用类似哪里你现在拥有的一切:

Product.find(:all, :conditions => ["exists (select * from Creators where product_id = Products.Id)"])

否则,我猜有活动记录加入数据,你也许可以得到由相同的方式包括创建者信息(假设你拥有的has_many设置),然后确保创建者信息存在...

Product.find(params[:id],:include => [:Creator],:conditions => ["Creator.product_id!=null"])

如果没有relati onships设置已经你需要在你的模型来定义,那么:

class Product< ActiveRecord::Base 
has_many :CreatorProduct 
has_many :Creators, :through => :CreatorProduct