So I was able to find a fix for the issue and handled the routing issue and redirection. The subscription gets updated and selected and also the data is added into the database.
I updated the routes like this
resources :subscriptions, only: [:new, :create] do
collection do
get ‘renew’
patch ‘update’
end
end
Then I updated the create and update functions of the subscriptions controller
def create
admin_id = @admin.id
puts “Admin ID when creating: #{admin_id}”
selected_policy = Admin::POLICIES.find { |policy| policy[:name] == params[:subscription_type] }
if selected_policy
begin
if @admin.update(
subscription_type: selected_policy[:name],
subscription_start_date: Date.today,
subscription_end_date: Date.today + selected_policy[:duration]
)
redirect_to root_path, notice: ‘Subscription successfully created.’
else
puts “Validation errors: #{@admin.errors.full_messages.join(', ')}”
redirect_to new_subscription_path, alert: ‘Failed to create subscription.’
end
rescue => e
puts “Exception during update: #{e.message}”
redirect_to new_subscription_path, alert: ‘An error occurred while creating the subscription.’
end
else
redirect_to new_subscription_path, alert: ‘Invalid subscription type.’
end
admin_id = @admin.id
puts “Admin ID after creating: #{admin_id}”
end
def update
admin_id = @admin.id
puts “Admin ID when updating: #{admin_id}”
selected_policy = Admin::POLICIES.find { |policy| policy[:name] == params[:subscription_type] }
if selected_policy
new_end_date = @admin.subscription_end_date || Date.today
if @admin.update(
subscription_type: selected_policy[:name],
subscription_start_date: Date.today,
subscription_end_date: new_end_date + selected_policy[:duration]
)
redirect_to root_path, notice: ‘Subscription successfully renewed.’
else
puts “Validation errors: #{@admin.errors.full_messages.join(', ')}”
redirect_to renew_subscriptions_path, alert: ‘Failed to renew subscription.’
end
else
redirect_to renew_subscriptions_path, alert: ‘Invalid subscription type.’
end
admin_id = @admin.id
puts “Admin ID when updated: #{admin_id}”
end
After that I updated the form_path for new page like this
<%= form_with(model: @subscriptions, url: subscriptions_path, method: :post) do |form| %>
And for the renew page like this
<%= form_with(model: @subscriptions, url: subscriptions_path, method: :patch) do |form| %>
Now the subscription policy is getting added and renewed for the designated admin.