我有两个模型产品和类别。检索导轨关联的反向多个记录
我能做出这样Category.products等
成功查询Product.rb
belongs_to :category
Category.rb
has_many :products
现在我想找回只有那些至少有一个现有产品的类别。
我想是这样的:
@categories = Category.where(Category.products.present?)
#返回的错误未定义的方法`产品也改变产品没有工作。
Rails合并不会生成SQL UNION运算符。你的代码等于next:Category.joins(:products).where(with_operator:true).uniq – 2014-10-06 14:40:00
而不是合并的意图(阅读文档)。合并是告诉rails'with_operator'是产品表的条件,而不是类别表的条件。 – lcguida 2014-10-06 16:42:47
如果您运行'Category.joins(:products).where(with_operator:true).uniq'将返回一个错误,因为rails会认为'with_operator'是类别表 – lcguida 2014-10-06 18:01:42