在表单提交时更改标签的值 - Ruby on Rails



我正在复习我的轨道。我有一个非常简单的表格。视图→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时,页面将找不到calculatePOST 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>

最新更新