rails helper方法,用于查找文章是否属于某个类别

时间:2018-03-01 20:00:16

标签: ruby-on-rails helper has-many-through

我最近更新了我的知识库应用程序,通过关联获得了非常标准的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

我所拥有的其中一个类别是&#34;内部&#34;类别。我想要实现的是一个帮助方法,如果特定文章上设置了内部类别,我可以执行操作。如下所示:

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

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

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

这里你想要的只是一个简单的旧方法,因为它可以作用于self

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

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

稍后您可以根据需要将此代码重构为模块,但这与帮助程序不同。而是通过mixin模式进行并行继承。

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

您还想在dependent: :destroy联接表中设置categorizations选项。你设置它破坏文章的方式将破坏类别中的规范化行!

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