Skip to content

Commit

Permalink
improve @reflection class check
Browse files Browse the repository at this point in the history
  • Loading branch information
Paul-Bob committed Sep 6, 2024
1 parent 87742cb commit d30d552
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
24 changes: 14 additions & 10 deletions app/controllers/avo/associations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def new
def create
association_name = BaseResource.valid_association_name(@model, params[:related_name])

if reflection_class == "HasManyReflection"
if has_many_reflection?
@model.send(association_name) << @attachment_model
else
@model.send("#{association_name}=", @attachment_model)
Expand All @@ -80,7 +80,7 @@ def create
def destroy
association_name = BaseResource.valid_association_name(@model, params[:related_name])

if reflection_class == "HasManyReflection"
if has_many_reflection?
@model.send(association_name).delete @attachment_model
else
@model.send("#{association_name}=", nil)
Expand Down Expand Up @@ -127,12 +127,11 @@ def attachment_id
end

def reflection_class
reflection = @model.class.reflect_on_association(params[:related_name])

klass = reflection.class.name.demodulize.to_s
klass = reflection.through_reflection.class.name.demodulize.to_s if klass == "ThroughReflection"

klass
if @reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
@reflection.through_reflection.class
else
@reflection.class
end
end

def authorize_if_defined(method)
Expand All @@ -155,14 +154,19 @@ def authorize_detach_action
authorize_if_defined "detach_#{@field.id}?"
end

private

def set_related_authorization
@related_authorization = if related_resource
related_resource.authorization(user: _current_user)
else
Services::AuthorizationService.new _current_user
end
end

def has_many_reflection?
reflection_class.in? [
ActiveRecord::Reflection::HasManyReflection,
ActiveRecord::Reflection::HasAndBelongsToManyReflection
]
end
end
end
2 changes: 1 addition & 1 deletion app/controllers/avo/base_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def create
end

# For when working with has_one, has_one_through, has_many_through, has_and_belongs_to_many, polymorphic
if @reflection.is_a? ActiveRecord::Reflection::ThroughReflection
if @reflection.is_a?(ActiveRecord::Reflection::ThroughReflection) || @reflection.is_a?(ActiveRecord::Reflection::HasAndBelongsToManyReflection)
# find the record
via_resource = ::Avo::App.get_resource_by_model_name(params[:via_relation_class]).dup
@related_record = via_resource.find_record params[:via_resource_id], params: params
Expand Down

0 comments on commit d30d552

Please sign in to comment.