[英]Can I use validations on a Frozen_Record model in Ruby on Rails?
I'm using the gem Frozen Record in order to setup a series of invariable questions in my Rails app, which will be accessed and used by other models. 我正在使用宝石冻结记录 ,以便在Rails应用程序中设置一系列不变的问题,其他模型将访问和使用这些问题。 Given I'm used to Test Driven Development, I'd already set up a series of tests and validations before adding the Frozen Record gem:
鉴于我已经习惯了“测试驱动开发”,因此在添加“ Frozen Record” gem之前,我已经进行了一系列测试和验证:
class Question < FrozenRecord::Base
validates :next_question_id_yes, :question_text, :answer_type, presence: true
end
And the tests: 和测试:
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
All of these passed when I had the class Question < ActiveRecord::Base
but since becoming a FrozenRecord I get: 当我
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)
I presume there's no method in Frozen Record to validate the presence of these columns. 我认为Frozen Record中没有方法可以验证这些列的存在。 What I'm less sure of is:
我不太确定的是:
Any help would be appreciated. 任何帮助,将不胜感激。
Sorry to waste everyone's time - I just looked through the source code of FrozenRecord and worked out I can do it like this: 抱歉浪费大家的时间-我只是浏览了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
Should think before I ask next time. 我下次再问之前应该考虑一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.