Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jamesbebbington
Created October 10, 2017 13:12
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 jamesbebbington/2355eafc1ff53c036cfffa75e8d1f1ec to your computer and use it in GitHub Desktop.
Save jamesbebbington/2355eafc1ff53c036cfffa75e8d1f1ec to your computer and use it in GitHub Desktop.
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)
@jamesbebbington
Copy link
Author

jamesbebbington commented Oct 10, 2017

Modified from code posted here but I can't get it to work under Rails 5.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment