jayesh jayesh - 4 months ago 27
Ruby Question

how to validate rails form if will split form in multi tab?

we have rails model campaign and it had has_many location and camapign also has many groups and group has many tags
we like to have All validation must with server side.

My models are:

class Camapign < ActiveRecord::Base
has_many :locations
has_many :groups
attr_writer :current_tab
validates :name, :presence => true
validates :event_date, :presence => true
end

class Location < ActiveRecord::Base
validates :name, :presence => true
end

class Group < ActiveRecord::Base
has_many :tags
validates :name, :presence => true
validates :industry, :presence => true
end

class Tag < ActiveRecord::Base
validates :name, :presence => true
end


When i am creating Camapign i was creating Camapign with validate false and my view is in different tabs/portlet.

I need to validate only field which i have showed on form and if its not valid then it should navigate to proper error to respected tabs.

on first tab i have campaign name and locations
on second tab i have Groups name and tabs

i like to save all tabs details in to database with respected progress on tabs and at end conform and publish all details but i like to validate details ate intermediate tabs that i have on modal.

i have all operation on Camapign model with relational insert and i am tracking with current_tab attribute.

I able to validate Camapign modal field with current_tab values but not able to validate with other relational modal.

we not like to use any additional gem like wicked i like to make as simple as standard code so we have less dependency.

Please help us to validate form based on tabs and hoe to display error on tabs.

Answer

we can validation by before save events

class Camapign < ActiveRecord::Base
  has_many :locations
  has_many :groups
  attr_writer :current_tab
  validates :name, :presence => true
  validates :event_date, :presence => true

attr_writer :current_step # for access current tabs

         with_options :if => Proc.new { |campaign| campaign.current_step == "location"}  do |step|
            step.after_validation :validate_location_name
          end

    def validate_location_name
        self.locations.each do |location|
          if !location.name.present?
            location.errors.add(:name,"Invalid location")
            errors.add(:name,"Invalid location")
          end
        end
      end
end