【问题标题】:RAILS: Relations (Select all answers from all topics)RAILS:关系(从所有主题中选择所有答案)
【发布时间】:2016-09-23 17:07:32
【问题描述】:

category.rb

  has_many :topics

topic.rb

belongs_to :category
has_many :answers

answer.rb

belongs_to :topic

问题:

如何执行Category.first.topics.answers.count之类的查询

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 database-relations


    【解决方案1】:

    使用has_many :through 关系:

    # Category.rb
    has_many :topics
    has_many :answers, through: :topics
    

    现在您可以访问所有主题的所有答案,如下所示:

    Category.first.answers.count
    

    【讨论】:

      【解决方案2】:

      如果您设置了架构配置(即不使用has_many :through),您可能希望从Answers 开始并使用几个joins 来访问Category

      Answers.joins(topic: :category).where(categories: { id: category_id })
      

      这里我们加入一个嵌套关联,然后使用 where 子句通过 category_id 过滤掉

      注意:我认为这是正确的语法,但您可能需要摆弄topiccategory 的复数

      【讨论】:

      • 我真的忘记了 has_many :through,但是对于 1 个问题有很多解决方案总是很棒的。谢谢!
      猜你喜欢
      • 2022-11-13
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多