Use polymorphic routes to manage cards

We use a different logic to load the card depending on the controller
we're using, and then share the rest of the code. This way we simplify
the code a bit, since we don't have to check for the page_id parameter.
This commit is contained in:
Javi Martín
2021-01-06 20:09:36 +01:00
parent 04e817e696
commit 4c0bb894eb
12 changed files with 99 additions and 79 deletions

View File

@@ -1,7 +1,14 @@
class Admin::SiteCustomization::CardsController < Admin::SiteCustomization::BaseController
include Admin::Widget::CardsActions
load_and_authorize_resource :page, class: "::SiteCustomization::Page"
load_and_authorize_resource :card, through: :page, class: "Widget::Card"
def index
end
private
def index_path
admin_site_customization_page_widget_cards_path(@page)
end
end

View File

@@ -1,70 +1,10 @@
class Admin::Widget::CardsController < Admin::BaseController
include Translatable
include ImageAttributes
def new
if header_card?
@card = ::Widget::Card.new(header: header_card?)
else
@card = ::Widget::Card.new(site_customization_page_id: params[:page_id])
end
end
def create
@card = ::Widget::Card.new(card_params)
if @card.save
redirect_to_customization_page_cards_or_homepage
else
render :new
end
end
def edit
@card = ::Widget::Card.find(params[:id])
end
def update
@card = ::Widget::Card.find(params[:id])
if @card.update(card_params)
redirect_to_customization_page_cards_or_homepage
else
render :edit
end
end
def destroy
@card = ::Widget::Card.find(params[:id])
@card.destroy!
redirect_to_customization_page_cards_or_homepage
end
include Admin::Widget::CardsActions
load_and_authorize_resource :card, class: "Widget::Card"
private
def card_params
params.require(:widget_card).permit(
:link_url, :button_text, :button_url, :alignment, :header, :site_customization_page_id,
:columns,
translation_params(Widget::Card),
image_attributes: image_attributes
)
end
def header_card?
params[:header_card].present?
end
def redirect_to_customization_page_cards_or_homepage
notice = t("admin.site_customization.pages.cards.#{params[:action]}.notice")
if @card.site_customization_page_id
redirect_to admin_site_customization_page_cards_path(page), notice: notice
else
redirect_to admin_homepage_path, notice: notice
end
end
def page
::SiteCustomization::Page.find(@card.site_customization_page_id)
def index_path
admin_homepage_path
end
end