Created
October 10, 2017 13:12
-
-
Save jamesbebbington/2355eafc1ff53c036cfffa75e8d1f1ec to your computer and use it in GitHub Desktop.
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
module ActiveModelInstanceTagWithAssociations | |
def error_message | |
Rails.logger.debug "ActiveModelInstanceTagWithAssociations: " + @method_name.inspect | |
if @method_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(@method_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 == @method_name | |
end | |
end | |
if association.present? | |
object.errors[association.name] + super | |
else | |
super | |
end | |
end | |
end | |
ActionView::Helpers::ActiveModelInstanceTag.prepend(ActiveModelInstanceTagWithAssociations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modified from code posted here but I can't get it to work under Rails 5.1.