Skip to content

Instantly share code, notes, and snippets.

@edwardmp
Last active November 29, 2016 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardmp/805cc96aab2920a0c059fd6826f2abdf to your computer and use it in GitHub Desktop.
Save edwardmp/805cc96aab2920a0c059fd6826f2abdf to your computer and use it in GitHub Desktop.
Automatic bootstrap form validation on *_id fields when validates :association, presence: true is present
BootstrapForm::FormBuilder.class_eval do
def association_object(name)
name = name.to_s
if name.end_with?('_ids')
# Check for a has_(and_belongs_to_)many association (these always use the _ids postfix field).
association = object.class.reflect_on_association(name.chomp('_ids').pluralize.to_sym)
else
# Check for a belongs_to association with method_name matching the foreign key column
association = object.class.reflect_on_all_associations.find do |a|
a.macro == :belongs_to && a.foreign_key == name
end
end
return association
end
alias_method :super_has_error?, :has_error?
alias_method :super_get_error_messages, :get_error_messages
def has_error?(name)
association = association_object(name)
if association.present?
!object.errors[association.name].empty? || super_has_error?(name)
else
super_has_error?(name)
end
end
def get_error_messages(name)
assocation = association_object(name)
if assocation.present?
(object.errors[assocation.name] + super_get_error_messages(name).split(', ')).join(', ')
else
super_get_error_messages(name)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment