如果文本在rails模型中具有特定单词或字符串,则显示错误

时间:2014-06-28 08:42:28

标签: ruby-on-rails ruby

我有一个模型Question,其中包含以下字段:

  • question:text
  • answer_1:text
  • answer_2:text
  • answer_3:text
  • answer_4:text

我想在以下情况下不允许提问:

  • 问题中包含"not""except"字样,
  • 在答案字段中添加"none of the above""all of the above"字样,
  • 从答案字段中的"true""false""yes""no"开始,或
  • 答案中有"answer is"

3 个答案:

答案 0 :(得分:1)

您可以在模型中创建自定义验证器:

validate :check_words, :on => :create
NOT_ALLOWED_WORDS = ["not", "except"]

 def check_words 
  errors.add :question, "not allowed" unless (NOT_ALLOWED_WORDS - only_words_from_question) == NOT_ALLOWED_WORDS
end


def only_words_from_question
  self.question.split(/\W+/)
end

如果在创建后有任何“不允许”的单词,在obj.errors.full_messages中应该是“不允许”错误。

我认为这就是你要找的东西。

答案 1 :(得分:0)

如果http://guides.rubyonrails.org/active_record_validations.html#exclusion不适合您,您可以尝试使用正则表达式:

在您的控制器中,例如:

@question = Question.new(question_params)
if params[:question] =~  /not/ || params[:answer] =~ /all of the above/ || what-so-ever-conditions
   raise "not accepted"
else
   @question.save
end

然而,这不是一个好的解决方案,相反,你应该尝试@pavan在评论中提到的内容。

答案 2 :(得分:0)

以下是我如何解决我的问题。

validate :check_question, :on => :create
DISALLOW_QUESTION = ["not", "except"]

def check_question 
  DISALLOW_QUESTION.each do |w|
      errors.add :question, "shouldn't have '#{w}'", if question.include? w
  end
end

validate :check_answer, :on => :create
DISALLOW_ANSWER = ["none of the above", "all of the above", "answer is"]
START_WITH = ['true', 'false', 'yes', 'no']

def check_answer 
  DISALLOW_ANSWER.each do |w|
    errors.add :answer_1, "shouldn't have '#{w}'" if answer_1.include? w
    errors.add :answer_2, "shouldn't have '#{w}'" if answer_2.include? w
    errors.add :answer_3, "shouldn't have '#{w}'" if answer_3.include? w
    errors.add :answer_4, "shouldn't have '#{w}'" if answer_4.include? w
  end
  START_WITH.each do |w|
    errors.add :answer_1, "can't start with '#{w}'" if answer_1.start_with? w
    errors.add :answer_2, "can't start with '#{w}'" if answer_2.start_with? w
    errors.add :answer_3, "can't start with '#{w}'" if answer_3.start_with? w
    errors.add :answer_4, "can't start with '#{w}'" if answer_4.start_with? w
  end
end