nicodo
nicodo

Reputation: 47

Rails - link_to - delete action - how to redirect to another page using another controller action inside a link_to

Is there any way in Rails to delete and redirect differently from what defined in the controller destroy action?

On the deal show view I have:

<% @deal.tenants.each do |guy| %>
  <li>Tenant id #<%= guy.id %> - <%= link_to guy.last_name, deal_tenant_path(@deal, guy)  %> 
  <%= link_to "delete", deal_tenant_path(@deal, guy), method: :delete, data: { confirm: "Are you sure you want to delete this tenant?"} %></li>
<% end %>

On the tenant show view I have:

<li><%= link_to "Delete Tenant", [@deal, @tenant], method: :delete,
 data: { confirm: "Are you sure you want to delete this tenant?"},
 class: "delete" %></li>

On the tenant index view I have

<% @deal.tenants.each do |tenant| %>
  <li>Tenant id #<%= tenant.id %> - <%= link_to tenant.last_name, [@deal, tenant] %></li>
  <li><%= link_to "Delete Tenant", deal_tenant_path(tenant.deal, tenant), method: :delete, data: { confirm: "Are you sure you want to delete this tenant?"} %></li>
<% end %>

In line with my controller I am redirected to the @deal show when deleting. tenants_controller.rb

def destroy
  @tenant.destroy
  flash[:notice] = "Tenant has been deleted."
  redirect_to @deal
end

What if I want to be redirected differently each time ? Let's say I want to stay on the tenant show view when deleting on that page instead of being redirected to the deal show page. Alternatively I would like to be redirected to the tenant index view etc.

Do I need to define different actions with different redirections in the tenants controller or can I do it inside the link_to?

Nested routes:

resources :deals, only: [:index, :show, :create, :update, :destroy] do
  scope '/siteadmin' do
    resources :tenants
  end
end

scope '/siteadmin' do
  resources :deals, except: [:index, :show]
end

Deal.rb

class Deal < ApplicationRecord
  has_many :tenants, dependent: :destroy
end

Tenant.rb

class Tenant < ApplicationRecord
  belongs_to :deal
  validates :deal_id, :first_name, :last_name, :age, presence: true
end

Upvotes: 2

Views: 2045

Answers (1)

KcUS_unico
KcUS_unico

Reputation: 513

It can not be done by the link_to because the action will be called in your controller. But you can of course change the redirect_ to @deal to

redirect_to :back 

or redirect_to what_ever_path

You can always create different actions or you pass params with your link_to and add a line to your current controller action like:

if params[:tenant]
redirect_to :back 
else 
redirect_to @deal

Answers your question?

Upvotes: 1

Related Questions