corix010
corix010

Reputation: 571

Rails validation on fields not tied to any model

I have a rails app with the following form:

<%= form_tag(:action => 'index') do %>
  From: <%= text_field_tag(:from, params[:from]) %><br />
  To: <%= text_field_tag(:to, params[:to]) %><br />
  <%= submit_tag("Submit") %>
<% end %>

Which displays a listing based on the date range provided by the :from and :to params.

How do I do presence and compare validations on the two text boxes which are not tied to any model or table?

Thanks! Corix

Upvotes: 0

Views: 149

Answers (1)

Chris Mohr
Chris Mohr

Reputation: 3929

You can use a model that's not persisted to the database.

class DateRange
  include ActiveModel::Validations

  attr_accessor :from, :to
  validates_presence_of :from, :to

  def persisted?
    false
  end
end

Then in the controller:

date_range = DateRange.new(:from => params[:from], :to => params[:to])
if date_range.valid?
  #do stuff
end

Upvotes: 1

Related Questions