简体   繁体   English

Rails - 在动作之间保存参数

[英]Rails - Save parameters between actions

I have an app that books spaces for certain dates.我有一个应用程序可以为某些日期预订空间。 In the index page, I have a search form to display only the spaces that are available from params[:query1] to params[:query2] certain dates.在索引页面中,我有一个搜索表单,仅显示从params[:query1]params[:query2]某些日期可用的空格。 Then in the space show page, I have a form for booking the space.然后在空间展示页面,我有一个预订空间的表格。

I'd like to maintain the params[:query1] and params[:query2] also in the space show page as the default value for the booking form.我想在空间显示页面中也保留params[:query1]params[:query2]作为预订表单的默认值。

index.html.erb:索引.html.erb:

<%= form_tag spaces_path, method: :get, class: "form-inline" do %>
  <%= label_tag :query1, "Check in" %>
  <%= date_field_tag :query1, params[:query1], class: "form-control" %>
  <%= label_tag :query2, "Check out" %>
  <%= date_field_tag :query2, params[:query2], class: "form-control" %>
  <%= submit_tag "Search", class: "btn" %>
<% end %>

show.html.erb显示.html.erb

<%= form_with(model: [@space, @booking], local: true) do |f| %>
  <%= label_tag :check_in, "Check in" %>
  <%= f.date_field :check_in, value: params[:query1], class: "form-control" %>
  <%= label_tag :check_out, "Check out" %>
  <%= f.date_field :check_out, value: params[:query2], class: "form-control" %>
  <%= submit_tag "Reserve", class: "btn" %>
<% end %>

You can use a session to store your queries and use them throughout your app.您可以使用 session 来存储您的查询并在整个应用程序中使用它们。 You can store your queries in a session in your index action like this:您可以在索引操作中将查询存储在 session 中,如下所示:

def index
  session[:query1] = params[:query1]
  session[:query2] = params[:query2]
end

Then in your show action, you can access the session like this:然后在您的显示操作中,您可以像这样访问 session:

def show
  @query1 = session[:query1]
  @query2 = session[:query2]
end

In your form on your show page, you can then use the instance variables:在显示页面上的表单中,您可以使用实例变量:

<%= form_with(model: [@space, @booking], local: true) do |f| %>
  <%= label_tag :check_in, "Check in" %>
  <%= f.date_field :check_in, value: @query1, class: "form-control" %>
  <%= label_tag :check_out, "Check out" %>
  <%= f.date_field :check_out, value: @query2, class: "form-control" %>
  <%= submit_tag "Reserve", class: "btn" %>
<% end %>

Learn more about session了解更多关于session

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM