(モデルやオブジェクトからではなく)配列から取得した多くのフィールドを持つフォームがあります。これらのフィールドの存在をどのように検証できますか?
<%= 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/