Created
August 23, 2021 19:10
-
-
Save anlek/9f888518d3273508caffafdb1afea07c to your computer and use it in GitHub Desktop.
Support ActiveRecord setting id columns on belong_to relationships
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 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