1

我有一个 Product 和 Creator 表,我还有一个名为 CreatorProduct 的表,它将创建者与产品连接起来。一个产品可以有很多创作者,一个创作者可以有很多产品。我想做的是找到有创作者的产品,有些产品可能没有创作者。

我已经编写了下面的代码,但是如何以更友好的方式编写它?这适用于我的 in rails 控制台,但是当我将其放入代码中时,我得到未定义的方法 `includes' for #

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

谢谢!

4

1 回答 1

0

I would probably just use the find function and use a similar where to what you have now:

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

Otherwise I guess with the way active record joins the data you could probably get the same by including the creator information (assuming you have the has_many set up) and then make sure that the creator information exists...

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

If you don't have the relationships set up already you need to define then in your models:

class Product< ActiveRecord::Base
has_many :CreatorProduct
has_many :Creators, :through => :CreatorProduct
于 2011-11-21T18:47:23.907 回答