我有一个Rails博客,文章可以有多个类别-如何构造我的ArticlesController索引操作以匹配给定的类别ID?

时间:2018-07-25 00:41:43

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

所以我有一个Rails博客,其中的文章可以有很多类别,类别可以有很多文章,通过ArticleTags连接表进行桥接,如下所示:

class Article < ApplicationRecord
  ...
  has_many :article_tags,
    primary_key: :id,
    foreign_key: :article_id,
    class_name: 'ArticleTag'

  has_many :categories,
    through: :article_tags,
    source: :category
end

class Category < ApplicationRecord
  ...
  has_many :article_tags,
    primary_key: :id,
    foreign_key: :category_id,
    class_name: 'ArticleTag'

  has_many :articles,
    through: :article_tags,
    source: :article
end

class ArticleTag < ApplicationRecord
  belongs_to :article,
    primary_key: :id,
    foreign_key: :article_id,
    class_name: 'Article'

  belongs_to :category,
    primary_key: :id,
    foreign_key: :category_id,
    class_name: 'Category'
end

如果我的路线是“ / categories /:id / articles”,我只想返回与该类别id匹配的文章,但是我不确定如何构造我的控制器索引动作。我知道了:

class Api::ArticlesController < ApplicationController
  def index
    if params[:category_id]
#     @articles = Article.where(????)
    else
      @articles = Article.all
    end
    render :index
  end
  ...

非常感谢!

1 个答案:

答案 0 :(得分:1)

尝试以下操作:Tax4FunOutput <- Tax4Fun(QIIMESingleData, "SILVA123", fctProfiling = TRUE, refProfile = "UProC", shortReadMode = TRUE, normCopyNo = TRUE) c.f:https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html