簡體   English   中英

從link_to重定向到另一個控制器,在rails中使用remote => true

[英]redirect_to another controller from link_to with remote=>true in rails

在Rails項目中,我有2個控制器,我使用link_toremote => true來創建新的assignmenttable 我有以下代碼:

assignmettables_controller.rb

class AssignmenttablesController < ApplicationController
  before_action :set_assignmenttable, only: [:show, :edit, :update, :destroy]

  def new
    @assignmenttable = Assignmenttable.new
  end

  def create
    @assignmenttable = Assignmenttable.new
    @assignmenttable.current_user_id = params[:current_user_id]
    @assignmenttable.task_id = params[:task_id]

    respond_to do |format|
      if @assignmenttable.save
        format.html { redirect_to new_reporter_path, notice: 'Assignmenttable was successfully created.' }
        format.json { render action: 'show', status: :created, location: @assignmenttable }
      else
        format.html { render action: 'new' }
        format.json { render json: @assignmenttable.errors, status: :unprocessable_entity }
      end
    end
  end
end

views/assignmettables/_form.html.erb

<%= link_to "submit", assignmenttables_path(:current_user_id => user.id, :task_id => params[:task_id]), :remote => true,  :method => "post" %>

現在,當我點擊submit ,這2個參數傳遞給create在控制器和新的行動assignmenttable在數據庫中創建的,我想在assignmenttable保存,頁面是redirect_to另一個控制器( new_reporter_path ),但頁面留在assignmettable/new並且不會發生任何動作。 我怎樣才能做到這一點?(重定向頁面new_reporter_path保存后assignmenttable在數據庫中,然后顯示一個消息)。

您需要閱讀此內容 使用link_to remote:true時,將頁面請求替換為ajax請求。 因此,您的重定向將保留在此ajax請求內,而不會在瀏覽器中發生。 因此,您有兩種可能的解決方案:

  1. 刪除遠程:true,因為您需要在操作后重定向用戶,所以沒有用這種方式來取消該請求。
  2. 在Ajax請求成功時重定向到客戶端(請參閱我的答案中的第一個鏈接)。

但是第二種解決方案是愚蠢的,因為在該請求中使用ajax的唯一原因是避免頁面重新加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM