Skip to content

Instantly share code, notes, and snippets.

@anlek
Created August 23, 2021 19:10
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 anlek/9f888518d3273508caffafdb1afea07c to your computer and use it in GitHub Desktop.
Save anlek/9f888518d3273508caffafdb1afea07c to your computer and use it in GitHub Desktop.
Support ActiveRecord setting id columns on belong_to relationships
module EnhancedAssociationIdSetter
extend ActiveSupport::Concern
module ClassMethods
def belongs_to(name, scope = nil, **options)
result = super
build_assocation_id_setter_for(name)
result
end
def build_assocation_id_setter_for(assocation)
reflection = reflections[assocation.to_s]
raise "Unable to find #{assocation} for #{model_name.class_name}" unless reflection
id_column = reflection.foreign_key
association_klass = reflection.class_name
class_eval <<~RUBY, __FILE__, __LINE__ + 1
def #{id_column}=(value)
new_value = value.is_a?(#{association_klass}) ? value.id : value
self[:#{id_column.to_sym}] = new_value
end
RUBY
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment