【发布时间】:2015-12-06 00:05:58
【问题描述】:
我有两个模型:Category 和 Post,它们通过 categories_posts 表连接。类别可以通过category_id字段有子类别,与父类别字段的id相关。帖子可以有多个类别(父类别和子类别,或者例如只有一个子类别)。
类别:
has_and_belongs_to_many :posts
has_many :categories, class_name: "Category", foreign_key: "category_id"
belongs_to :category, class_name: "Category"
帖子:
has_and_belongs_to_many :categories
has_and_belongs_to_many :get_categories, class_name: 'Category'
一切正常,我可以获得一个特定类别的帖子:
Category.find(params[:id]).posts
但无法获取具有自己子类别的类别的帖子,如下所示:
Category.where('`id` = :id OR `category_id` = :id', :id => params[:id]).posts
Rails 控制台返回:undefined method 'posts' for #<Category::ActiveRecord_Relation:0x00000110f9be40>
我为此编写了正确的 SQL 查询,但我需要通过 ActiveRecord 在 Rails 4 中编写相同的查询。
SELECT DISTINCT posts.* FROM posts INNER JOIN categories_posts ON posts.id = categories_posts.post_id WHERE categories_posts.category_id IN (3,10) ORDER BY posts.date DESC
【问题讨论】:
标签: ruby-on-rails activerecord