Rails - Show/hide CSS class 当参数存在于 URL

Rails - Show/hide CSS class when parameter exist in URL

在我看来,我有一个表单,我只想在其参数出现在 URL:

中时显示输入
= form_tag search_path, :method => :get do
  = select_tag 'search[type]', options_for_select([['Publishers', 'publishers'], ['Editions', 'editions'], ['Contributors', 'contributors']], selected = (params[:search][:type] rescue nil)), prompt: "Search type", :required => "true"

  = select_tag 'search[filter]', options_for_select([['Filter by', 'filter_by'], ['All', 'all']], selected = (params[:search][:filter] rescue nil)), prompt: "Select filter", :required => "true"

  - invisible = params[:search][:value].present? ? '' : 'invisible'
  = text_field_tag 'search[value]', (params[:id] || params[:search][:value] rescue nil), :required => "true", :class =>  "#{invisible}", :placeholder => "Type search"

我的想法是控制它显示一个名为 "invisible" 和 display: none; 的 CSS class,如上所述。但是当我渲染视图时 returns 在我声明 "invisible":

的行中出现此 Rails 错误
undefined method `[]' for nil:NilClass

怎么了?

这是因为当表单加载时,params[:search] 为 nil,而您正试图对其调用 [:filter],因此未定义方法 [] 为 nil。

有多种解决方案,有些不错,有些不太好,选择您最喜欢的:

invisible = params[:search].try(:[], :value) ? '' : 'invisible'
invisible = params[:search] && params[:search][:value] ? '' : 'invisible'
invisible = (params[:search] || {})[:value] ? '' : 'inivisble'
invisible = (params[:search][:value] rescue nil) ? '' : 'invisible'
...

- invisible = params[:search].try(:[], :filter).blank? ? 'invisible' : ''

...

这是因为 params[:search]nil 而你正在调用 params[:search][:filter]

尝试:

invisible = params[:search].present? ? (params[:search][:filter].present? ? '' : 'invisible') : ''