我正在复习我的轨道。我有一个非常简单的表格。视图→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 %>
我在controllers下有一个controller ->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
如何,当我填写从文本:查询和点击提交,我可以得到文本表示在我的视图的最后,以显示我放入2倍的值(每计算函数)?看起来应该很容易,但显然我忘记了表单和表单提交的一些基本原则。
将渲染改为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 %>
查看您的路由文件,您在提交calculate
的post请求时调用index
动作,因此它总是从索引方法返回@query值,即biznass
如果你想使用params计算@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
我建议在路由中使用resources
。而不是那样做,它会更简洁,可伸缩,你可以使用url helper方法。你可以在你的终端上运行rake routes
来查看路由的细节,比如helper方法的名称,路径,http动词,以及路径正在使用哪个控制器的方法。
resources :genalg, controller: :genalg, only: [:index] do
collection do
post :calculate
end
end
在def calculate
的这个实例中,如果你有http动词POST
的方法,它应该以成功状态响应,大多数时候你需要重定向它而不是渲染它,因为当用户在calculate
之后刷新或复制url时,页面将找不到calculate
有POST
http动词。因此,您必须将render
更改为redirect_to
并传递参数: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
那么在index中可以检查params query是否为空
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>