Skip to content

Instantly share code, notes, and snippets.

@tjbarker
tjbarker / active_admin.rb
Created August 27, 2021 05:59
active admin, polymorphic drop down
# 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
@tjbarker
tjbarker / relationship_example
Created October 14, 2020 02:17
Difference between checking presence of child association between active record relation and ransack
# 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