在模块中使用has_many

时间:2018-02-07 14:29:26

标签: ruby-on-rails

我有一个模型评估,其中has_many的模型标记为evaluate_tags

我需要在此模块中添加此关系,但我不知道我该怎么做

class Evaluation < ApplicationRecord
    belongs_to :user
    belongs_to :teacher
    belongs_to :school
    belongs_to :subject

    has_many :evaluation_tags
    has_many :tags, through: :evaluation_tags

    accepts_nested_attributes_for :evaluation_tags

    validates :teacher_id, presence: true
    validates :subject_id, presence: true
    validates :school_id, presence: true
    validates :user_id, presence: true
    validates :rating, presence: true
end

module Wizard
  module Evaluation
    STEPS = %w(step1 step2 step3).freeze

    class Base
      include ActiveModel::Model
      attr_accessor :evaluation

      delegate *::Evaluation.attribute_names.map { |attr| [attr, "#{attr}="] }.flatten, to: :evaluation

      def initialize(evaluation_attributes)
        @evaluation = ::Evaluation.new(evaluation_attributes)
      end
    end

    class Step1 < Base
      validates :teacher_id, presence: true
    end

    class Step2 < Step1
      validates :subject_id, presence: true
    end

    class Step3 < Step2
      validates :school, presence: true
      validates :user, presence: true
      validates :rating, presence: true
    end
  end
end

当我访问step3页面时,会出现此错误

的未定义方法`tag_ids'

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我认为您可以使用ActiveSupport::Concern,如下所示:

module Wizard
  module Evaluation
    extend ActiveSupport::Concern

    included do
      has_many :tags, through: :evaluation_tags
    end
  end
end

然后你的班级需要加入它:

class Evaluation
  include Wizard::Evaluation
end