簡體   English   中英

Rails-控制器中的Redirect_to錯誤-“頁面未正確重定向”

[英]Rails - Redirect_to error in controller - “The page isn't redirecting properly” "

在學習Rails的過程中,請原諒我的新手問題。

我想做什么:有一個text_field_tag,允許用戶輸入項目ID。 然后,我想獲取該值並將其用作url中的參數。 例如 用戶在文本框中鍵入“ 4Qe6”,然后單擊“提交”。 然后頁面導航到“ trckr.net/tracker/track/4Qe6”

這是我的表單的代碼:

<h1>Tracker#index</h1>
<p>This is the landing page</p>
<p>
  <u> Track an item: </u>
  <%= form_tag(:action => 'track') do %>
    Item ID: <%= text_field_tag(:id) %>

    <%= submit_tag('Track Item') %>
  <% end %>
</p>

在TrackerController中:

class TrackerController < ApplicationController
  def index
  end

  def track
    puts "navigating to track view"
    @id = params[:id]
    redirect_to "/tracker/track/#{@id}" 
  end
end

但是我收到錯誤消息:頁面未正確重定向-Firefox檢測到服務器正在以永遠無法完成的方式重定向對該地址的請求。

但是,如果我直接鏈接到這樣的頁面:

<%= link_to("Track item 2", {:action => 'track', :id => '6969'}) %>

工作正常。 這是我運行rake routes時的輸出:

Calvins-Air:trckr Calvino$ rake routes
root  /                                      tracker#index
      /:controller(/:action(/:id))(.:format) :controller#:action

如果使用其他操作,則無法使用在控制器中設置的實例變量。

新的控制器代碼:

  def track
    puts "navigating to track view"
  end

  #redirects to track after retrieving the url parameters
  #want a url parameter so users can link to the page
  def track_helper
    @id = params[:id]
    redirect_to "/tracker/track/#{@id}"
  end

但隨后無法訪問軌跡視圖@id:

<h1>Tracker#track</h1>
<p>This page will be used to view an items details</p>
<p><b>Item id: <%= @id %> </b></p>

<%= link_to("Back to index" , {:action => 'index'}) %>

編輯:通過在跟蹤操作中聲明@id變量來修復最后一個錯誤。 固定代碼:

 def track
    puts "navigating to track view"
    @id = params[:id]
  end

我猜這是因為您的重定向路徑是由發送此請求的位置的相同操作(和控制器)處理的。 您可以為其創建新動作,也可以將其路由到其他處理程序。

暫無
暫無

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

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