我正在刷我的鐵軌。我有一個簡單的表格。視圖 -> genalg -> index.html.erb
<h1>Genalg#index</h1>
<p>Find me in app/views/genalg/index.html.erb</p>
<%= form_with url: "/calculate" do |form| %>
<%= form.text_field :query %>
<%= form.submit "calculate" %>
<% end %>
<% unless @query.nil? %>
<p><%=@query%></p>
<% end %>
我在控制器下有一個控制器 - > genalg_controller.rb
class GenalgController < ApplicationController
def index
@query = "biznass"
end
def calculate
puts params
@query = (params[:query].to_i * 2).to_s
render :index
end
end
在 routes.rb 中:
Rails.application.routes.draw do
get 'genalg/index'
post '/calculate', to: 'genalg#index' , as: 'index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
如何,當我填寫 from text :query 并點擊提交時,我能否獲得在視圖最后表示的文本以顯示我輸入的值 2(根據計算函式)?似乎應該很容易,但顯然我忘記了表單和表單提交如何作業的一些基本租戶。
uj5u.com熱心網友回復:
將渲染更改為 redirect_to 并像這樣傳遞引數
def calculate
puts params
@query = (params[:query].to_i * 2).to_s
redirect_to index_path(query: @query)
end
<% unless params[:query].blank? %>
<p><%=@query%></p>
<% end %>
uj5u.com熱心網友回復:
查看您的路線檔案,您正在呼叫index提交發布請求的操作calculate因此它始終從索引方法回傳 @query 值,即biznass
如果要使用引數計算 @query 并使用定義相同路由的索引操作,則必須更新索引方法
def index
if params[:query]
puts params
@query = (params[:query].to_i * 2).to_s
else
@query = 'biznass'
end
或者您可以更改路線和控制器代碼
Rails.application.routes.draw do
get 'genalg/index'
post 'genalg/calculate'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
class GenalgController < ApplicationController
def index
@query = params[:query] || "biznass"
end
def calculate
puts params
@query = (params[:query].to_i * 2).to_s
redirect_to index_path(query: @query)
end
end
uj5u.com熱心網友回復:
我建議resources在你的 routes.rb 中使用,而不是那樣做,它會更加簡潔,可擴展,你可以使用 url helper 方法。您可以rake routes在終端中運行以查看路由的詳細資訊,例如輔助方法的名稱、路徑、http 動詞以及路徑正在使用哪個控制器的方法。
resources :genalg, controller: :genalg, only: [:index] do
collection do
post :calculate
end
end
在這種情況下def calculate,如果你有帶有 http 動詞的方法POST并且它應該以成功狀態回應,大多數時候你需要重定向它而不是渲染它,因為如果用戶重繪 或復制 url 之后calculate,頁面將不會被發現calculate有POSThttp 動詞。所以你必須改變render并redirect_to傳遞 params :query,所以每次用戶在計算后重繪 頁面時,:query都會被持久化。即使您想存盤:query在資料庫中,這仍然適用。另外,在這里你可以看到我們使用輔助方法重定向到索引頁面genalg_index_path
def calculate
puts params
query = (params[:query].to_i * 2).to_s
redirect_to genalg_index_path(query: query)
end
然后在索引中您可以檢查引數查詢是否為空
def index
@query = params[:query] || 'biznass'
end
如您所見,我們再次使用輔助方法來獲取計算路徑,并且我們不需要@query條件,因為它從不nil
<h1>Genalg#index</h1>
<p>Find me in app/views/genalg/index.html.erb</p>
<%= form_with url: genalg_calculate_path do |form| %>
<%= form.text_field :query %>
<%= form.submit 'calculate' %>
<% end %>
<p><%=@query%></p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530364.html
標籤:轨道上的红宝石红宝石形式
