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

问题描述 投票:0回答:1

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

我所拥有的类别之一是“内部”类别。我想要实现的是一个帮助方法,如果特定文章上设置了内部类别,我可以执行操作。类似于以下内容:

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

任何帮助将不胜感激!

ruby-on-rails helper has-many-through
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.