【问题标题】:Rails: Find records in nested HABTM relationRails:在嵌套的 HABTM 关系中查找记录
【发布时间】: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


    【解决方案1】:

    您正在引用属于类别实例数组上的类别实例的帖子关系。如果您想急切加载帖子,您可以添加.includes(:posts)。我不确定您的最终用途是什么,但这就是问题所在。

    但是,如果您想加载具有该类别或子类别的所有帖子,请从 Post 模型中执行此操作,如下所示:Post.includes(:categories).where('categories.id = :id OR categories.category_id = :id, id: params[:id]).references(:categories)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多