[英]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? 在Rails中,有什么方法可以与控制器destroy操作中定义的方法不同的方式进行删除和重定向?
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. 与我的控制器一致,删除时我将重定向到@deal show。 tenants_controller.rb
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? 我是否需要在租户控制器中定义具有不同重定向的不同操作,或者可以在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 Deal.rb
class Deal < ApplicationRecord
has_many :tenants, dependent: :destroy
end
Tenant.rb Tenant.rb
class Tenant < ApplicationRecord
belongs_to :deal
validates :deal_id, :first_name, :last_name, :age, presence: true
end
It can not be done by the link_to because the action will be called in your controller. link_to无法完成此操作,因为该操作将在您的控制器中调用。 But you can of course change the redirect_ to @deal to
但是您当然可以将redirect_更改为@deal,
redirect_to :back
or redirect_to what_ever_path 或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: 您可以始终创建其他操作,也可以使用link_to传递参数,并在当前的控制器操作中添加一行,例如:
if params[:tenant]
redirect_to :back
else
redirect_to @deal
Answers your question? 回答您的问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.