Last active
November 29, 2016 16:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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