ruby-on-rails – 如何验证非模型(甚至非对象)字段
发布时间:2020-12-17 03:36:26 所属栏目:百科 来源:网络整理
导读:我有一个从数组中取出很多字段的表单(不是来自模型或对象).如何验证这些字段的存在? %= simple_form_for :solve,:url = solve_problem_path do |f| % % @input_variables.each do |label| % %= f.input label % % end % ...% end % 解决方法 创建一个简单的
我有一个从数组中取出很多字段的表单(不是来自模型或对象).如何验证这些字段的存在?
<%= simple_form_for :solve,:url => solve_problem_path do |f| %> <% @input_variables.each do |label| %> <%= f.input label %> <% end %> ... <% end %> 解决方法
创建一个简单的类来包装请求参数并使用ActiveModel :: Validations.
# defined somewhere,at the simplest: require 'ostruct' class Solve < OpenStruct include ActiveModel::Validations validates :foo,:bar,:presence => true # you could even check the solution with a validator validate do errors.add(:base,"WRONG!!!") unless some_correct_condition end end # then in your controller def your_method_name @solve = Solve.new(params[:solve]) if @solve.valid? # yayyyy! else # do something with @solve.errors end end 这样可以像模型一样验证,完成i18n错误消息等等. 编辑:根据您的评论,验证您可能做的一切: class Solve < OpenStruct include ActiveModel::Validations # To get the i18n to work fully you'd want to extend ActiveModel::Naming,and # probably define `i18n_scope` extend ActiveModel::Naming validate do # OpenStruct maintains a hash @table of its attributes @table.each do |key,val| errors.add(key,:blank) if val.blank? end end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |