ActiveRecord:“WHERE IN”SQL语句

时间:2011-06-25 01:24:23

标签: sql ruby-on-rails activerecord

我有以下SQL语句: SELECT article_id FROM publications WHERE category_id IN (SELECT id FROM categories WHERE parent_id = 3)

如何将其转换为Rails ActiveRecord?

我试过:Article.find(:all, :conditions => ["publications.category_id IN(?)", 3], :include => [:publications]),它返回空数组。

模特:

class Article < ActiveRecord::Base
  has_many :publications
  has_many :categories, :through => :publications

class Category < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Category'
  has_many :children, :class_name => 'Category', :foreign_key => :parent_id
  has_many :articles, :through => :publications
  has_many :publications


class Publication < ActiveRecord::Base
  belongs_to :article
  belongs_to :category

2 个答案:

答案 0 :(得分:3)

这有效吗?

Article.find(:all, 
             :conditions => ["publications.category_id IN(SELECT id FROM categories WHERE parent_id = ?)", 3], 
             :include => [:publications])

我建议您使用ancestry来表示数据库中的树结构,还有a railcast about ancestry

答案 1 :(得分:0)

你的模特是什么样的?

您需要在文章,类别和出版物模型中正确设置关联。

听起来您在表格中设置了相关的外键,但您的模型不知道要查找关联