Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a non-model (and even non-object) field

I have a form that has a lot of fields taken from an array (not from model or object). How can I validate the presence of these fields?

<%= simple_form_for :solve, :url => solve_problem_path do |f| %>
  <% @input_variables.each do |label| %>
    <%= f.input label %>
  <% end %>
  ...
<% end %>
like image 539
freemanoid Avatar asked Nov 27 '12 16:11

freemanoid


2 Answers

Create a simple class to wrap the request params and use 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

This gives you the benefit of validating like you would a model, complete with i18n error messages and so on.

EDIT: as per your comment, to validate everything you might do:

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
like image 141
numbers1311407 Avatar answered Sep 29 '22 22:09

numbers1311407


You can do the following with 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

EDIT :

This may be a much better solution : http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/

like image 40
Intrepidd Avatar answered Sep 29 '22 20:09

Intrepidd