我有以下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发布于 2011-06-25 09:38:52
这样行得通吗?
Article.find(:all,
:conditions => ["publications.category_id IN(SELECT id FROM categories WHERE parent_id = ?)", 3],
:include => [:publications])我建议你用ancestry来表示数据库中的树形结构,还有a railcast about ancestry
发布于 2011-06-25 09:39:44
你的模型是什么样子的?
您需要在文章、类别和发布模型中正确设置关联。
听起来您已经在表中设置了相关的外键,但是您的模型不知道如何查找关联
https://stackoverflow.com/questions/6475192
复制相似问题