rails 查找文章是否属于某个类别的辅助方法

rails helper method to find if article belongs to a certain category

我最近通过关联更新了我的知识库应用程序,使其具有相当标准的 has_many。以前文章属于一个类别,一个类别有很多文章。现在位置如下:

class Article < ApplicationRecord
  has_many :categorizations
  has_many :categories, :through => :categorizations

class Category < ApplicationRecord
  has_many :categorizations
  has_many :articles, :through => :categorizations, dependent: :destroy

class Categorization < ApplicationRecord
  belongs_to :article
  belongs_to :category

我拥有的类别之一是 "Internal" 类别。我想要完成的是一个辅助方法,如果特定文章设置了内部类别,我可以使用它来执行操作。类似于以下内容:

if @article.internal?
  do stuff
end

我认为它需要在 articles_helper.rb 文件中。

module ArticlesHelper

  def internal?
    figure out if @article has category "internal"
  end
end

我有以下信息,但我认为我走错了路,需要一些帮助:

def internal?
    @internal_cat = []
      @article.categories.each do |n|
        if (n.name == "Internal")
          @internal_cat = n.name
        end
      end
  end

如有任何帮助,我们将不胜感激!

这是辅助方法的错误用例。辅助方法用于简化和干燥您的视图,偶尔也用于控制器。例如,表单助手可以更轻松地创建表单并将模型绑定到输入。

助手是混合到视图上下文中的模块。

你在这里想要的只是你模型上的一个普通的旧方法,因为它可以作用于 self:

class Article < ApplicationRecord
  # ...
  def has_category?(name)
    categories.exists?(name: name)
  end

  def internal?
    has_category?("Internal")
  end
end

稍后您可以根据需要将此代码重构到模块中,但这与助手不同。而是通过混合模式并行继承。

module Categorized
  extend ActiveSupport::Concern
  included do
    has_many :categorizations, as: :resource
    has_many :categories, through: :categorizations
  end

  def has_category?(name)
    categories.exists?(name: name)
  end
end

class Article < ApplicationRecord
  include Categorized
end

class Video < ApplicationRecord
  include Categorized
end

您还想在 categorizations 加入 table 上设置 dependent: :destroy 选项。您设置销毁文章的方式将销毁类别中的规范化行!

class Article < ApplicationRecord
  has_many :categorizations, dependent: :destroy
  has_many :categories, through: :categorizations

class Category < ApplicationRecord
  has_many :categorizations, dependent: :destroy
  has_many :articles, through: :categorizations