Rails 5.我正在尝试制作一个简单的搜索表单,然后在控制器的索引中显示结果。不幸的是,我的“ search_params”在控制器和视图之间迷路了。
部分搜索
#_search.html.erb
<%= form_with( url: flights_path, method: "GET") do %>
<%= select_tag(:from, options_for_select(@airport_codes) ) %>
<%= select_tag(:to, options_for_select(@airport_codes)) %>
<%= number_field_tag(:passenger_count, 2, in: 1..10) %>
<%= select_tag(:date, options_for_select(@search_dates), include_blank: "(Any)", required: false ) %>
<%= submit_tag("Search") %>
<% end %>
提交控制台:
Parameters: {"utf8"=>"✓", "from"=>"YVR", "to"=>"YYC", "passenger_count"=>"2", "date"=>"", "commit"=>"Search"}
控制器:
#flights_controller.rb
class FlightsController < ApplicationController
def index
@search = search_params
@airport_codes = #list of airports
@search_dates = #list of future dates
@flight_results = Flight.search(search_params).includes(:to, :from)
end
def search_params
params.permit(:from, :to, :passenger_count, :date)
end
end
但是当我进入index.html.erb ...
#index.html.erb
<%= render "search" %>
<%= @search %>
@ search行显示为{}当我将@search放在控制器中时,控制台中的所有内容看起来都很好,但随后似乎消失了。我在这里错了吗?
好吧。问题出在行中:
params.permit(:from, :to, :passenger_count, :date)
为了将数据推送到视图,它需要在其中有一个'require'方法,如下所示:
params.require(:search).permit(:from, :to, :passenger_count, :date)
这意味着在搜索表单中手动重新配置每个标记行,如下所示:
<%= label_tag( "search[from]", "Departing from:") %>
我一定是在滥用助手。知道为什么需要'require'真是太好了。