Skip to content

Commit

Permalink
feature: apply target resource policy on belongs_to field create new …
Browse files Browse the repository at this point in the history
…link (#2934)

* feature: apply target resource policy on belongs_to field create new link

* fix polymorphic

* fix
  • Loading branch information
Paul-Bob authored Jul 3, 2024
1 parent 3cbaae8 commit 853a879
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,9 @@
<%= @form.hidden_field @field.id_input_foreign_key %>
<% end %>
<% end %>
<% if field.can_create? %>
<% create_href = create_path(Avo.resource_manager.get_resource_by_model_class(type.to_s)) %>
<% target_resource_for_type = Avo.resource_manager.get_resource_by_model_class(type.to_s) %>
<% if field.can_create?(target_resource_for_type) %>
<% create_href = create_path(target_resource_for_type) %>
<% if !disabled && create_href.present? %>
<%= link_to t("avo.create_new_item", item: type.model_name.human.downcase),
create_href,
Expand Down
8 changes: 6 additions & 2 deletions lib/avo/fields/belongs_to_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,12 @@ def index_link_to_record
end
end

def can_create?
@can_create
# field :user, as: :belongs_to, can_create: true
# Only can create when:
# - `can_create: true` option is present
# - target resource's policy allow creation (UserPolicy in this example)
def can_create?(final_target_resource = target_resource)
@can_create && final_target_resource.authorization.authorize_action(:create, raise_exception: false)
end

def form_field_label
Expand Down

0 comments on commit 853a879

Please sign in to comment.