简体   繁体   中英

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. 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.

index.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

<%= 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. You can store your queries in a session in your index action like this:

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

Then in your show action, you can access the session like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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