gpt4 book ai didi

css - Rails - 当 URL 中存在参数时显示/隐藏 CSS 类

转载 作者:行者123 更新时间:2023-11-28 08:39:08 24 4
gpt4 key购买 nike

在我看来,我有一个表单,我只想在其参数出现在 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”的 CSS 类,带有 display: none;,如上。但是,当我渲染 View 时,它会在我声明“不可见”的行中返回此 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'

关于css - Rails - 当 URL 中存在参数时显示/隐藏 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com