我有一个表单,其中有很多字段取自数组(不是来自模型或对象)。如何验证这些字段的存在?
<%= 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
您可以使用 attr_accessible 执行以下操作:
Class YourClass < ActiveRecord::Base
attr_accessible :field_1
attr_accessible :field_2
validates :field_1, :presence => true
validates :field_2, :presence => true
end
编辑 :
这可能是一个更好的解决方案:http: //yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/