content copied from Advanced Arel: When ActiveRecord Just Isn't Enough
further information:
content copied from Advanced Arel: When ActiveRecord Just Isn't Enough
further information:
# this is a helper method to provide setters for polymorphic relationships in active admin forms | |
# attribute_name: name that record knows polymorphic relationship as | |
# actions: the active record actions that should use this setter, defaults to setter being implemented before create and update | |
def polymorphic_attribute_set(attribute_name, actions: [:before_create, :before_update]) | |
klass = config.resource_class | |
foreign_key = klass.reflect_on_all_associations.find { |ref| ref.name == attribute_name }.association_foreign_key | |
setter = lambda do |rec| | |
record = ApplicationRecord.identifier_to_record(params[klass.name.snakecase][foreign_key]) | |
resource.send("#{attribute_name}=", record) | |
end |
# code set up | |
class Big < ApplicationRecord | |
has_many :littles | |
end | |
class Little < ApplicationRecord | |
belongs_to :big # foreign_key is the default littles.big_id | |
end | |
# in console |