tommyd456
tommyd456

Reputation: 10703

Rails errors array for form_tag forms

Rails 4 app.

Using form_tag to build a form and wanted to know the typical way (if there is one) for handling and displaying errors when the form is not backed my a model?

All the examples I find relate to a model and the typical @model.errors.any? view conditional but this won't do for form_tag.

Upvotes: 1

Views: 538

Answers (2)

geekdev
geekdev

Reputation: 1212

I would recommend to include ActiveModel::Validations on a class which doesn't behave model but we need validations.For an example, consider a Ticket class

Rails 4

class Ticket
  include ActiveModel::Model

  attr_accessor :title, :description

  validate_presence_of :title
  validate_presence_of :description
end

In addition for more details,if you see Rails 4 activemodel/lib/active_model/model.rb code for better understanding why in rails 4 "include ActiveModel::Model" only enough to make a class to behave like model.

def self.included(base)
  base.class_eval do
    extend ActiveModel::Naming
    extend ActiveModel::Translation
    include ActiveModel::Validations
    include ActiveModel::Conversion
  end
end

Rails 3

class Ticket
  include ActiveModel::Conversion
  include ActiveModel::Validations
  extend ActiveModel::Naming

  attr_accessor :title, :description

  validate_presence_of :title
  validate_presence_of :description
end

Your Ticket class behave like model that makes you to use these methods for error validations

 Ticket.new(ticket_params)
 @ticket.valid?
 @ticket.errors
 @ticket.to_param

I hope it may help you to solve your problems.

Upvotes: 1

medBouzid
medBouzid

Reputation: 8442

What you should do is :

first include ActiveModel::Model

then make accessor for your attributes

finally add validation to these attributes

For example if you have a contact model which you don't want to bind it with database

class Contact

  include ActiveModel::Model

  attr_accessor :name, :email, :message

  validates :name, presence: true
  validates :email, presence: true
  validates :message, presence: true, length: { maximum: 300 }
end

then in your view you can loop through your errors like you are using an habitual activeRecord Model

if @model.errors.any?
   # Loop and show errors.... 
end

Upvotes: 2

Related Questions