繁体   English   中英

我可以在Ruby on Rails中对Frozen_Record模型使用验证吗?

[英]Can I use validations on a Frozen_Record model in Ruby on Rails?

我正在使用宝石冻结记录 ,以便在Rails应用程序中设置一系列不变的问题,其他模型将访问和使用这些问题。 鉴于我已经习惯了“测试驱动开发”,因此在添加“ Frozen Record” gem之前,我已经进行了一系列测试和验证:

class Question < FrozenRecord::Base
 validates :next_question_id_yes, :question_text, :answer_type, presence: true
end

和测试:

require 'rails_helper'

RSpec.describe Question, :type => :model do
 let(:question) {Question.new(id: "1", question_text: "who's the daddy?", answer_type: 'Boolean', next_question_id_yes: '7', next_question_id_no: "9")}

 it 'is valid' do
    expect(question).to be_valid
 end

 #questions can be valid without a next_question_id_no, because some questions just capture info
 #questions must have a next_question_id_yes as that will route them to the subsequent question
 #if it's the last question in a block, we will use the next number up to signify the questions are complete
 it 'is invalid without a next_question_id_yes' do
    question.next_question_id_yes = nil
    expect(question).to_not be_valid
 end

  it 'is invalid without a question_text' do
    question.question_text = nil
    expect(question).to_not be_valid
 end

  it 'is invalid without an answer_type' do
    question.answer_type = nil
    expect(question).to_not be_valid
 end

end

当我class Question < ActiveRecord::Base时,所有这些都通过了,但是自从成为FrozenRecord以来,我得到了:

rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/frozen_record-0.4.0/lib/frozen_record/base.rb:78:in `method_missing': undefined method `validates' for Question:Class (NoMethodError)

我认为Frozen Record中没有方法可以验证这些列的存在。 我不太确定的是:

  1. 我是否需要对通过YAML加载的静态数据执行验证? 我的第一感觉是这将是对我的YAML代码的额外检查。
  2. 如果可以,我可以编写自定义验证来检查此数据吗?
  3. 有没有其他人使用过这个gem并使用Rspec克服了这个问题? (根据RubyGems,它已被下载了数千次)

任何帮助,将不胜感激。

抱歉浪费大家的时间-我只是浏览了FrozenRecord的源代码,并得出可以这样做的方法:

class Question < FrozenRecord::Base
  include ActiveModel::Validations
  validates :next_question_id_yes, :question_text, :answer_type, presence: true
  self.base_path = '/config/initializers/questions.yml'
end

我下次再问之前应该考虑一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM