提交搜索后保留搜索结果 (rails)
我希望在用户提交搜索后,他们选择的选项在搜索表单重新加载时保持选中状态。这是我针对这些选择框之一的代码:
<div><%= f.select :tod_like, Course.tod_array, {:include_blank => true, :selected => params[:search][:tod_like], :class=>"float_and_margin"} %></div>
关键代码是
:selected => params[:search][:tod_like]
当我刷新页面时,我收到以下错误:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
我知道我收到此错误,因为 params[:search][:tod_like] 为空。如何设置 :selected 使其在用户尚未提交表单时为空,但已提交,否则为空?我尝试使用三元运算符,但这不起作用。
谢谢!
I'd like to make it so that after users submit their search, the option they selected stays selected upon the search form's reload. Here's my code for one of these select boxes:
<div><%= f.select :tod_like, Course.tod_array, {:include_blank => true, :selected => params[:search][:tod_like], :class=>"float_and_margin"} %></div>
The key code is the
:selected => params[:search][:tod_like]
When I refresh my page, I get the following error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
I know I'm getting this error because there's params[:search][:tod_like] is blank. How do I set :selected so that it's blank if the user has not submitted a form, but is the submission, otherwise? I tried using a ternary operator, but that didn't work.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
params key 是否正确?
我认为形式 f 是 Course 的一个实例,所以它不是像
@course.tod_like = params[:search][:tod_like] 吗? params[:search][:tod_like] : ""
位于生成搜索函数的函数顶部(您已经提到您已经尝试过三元语句,但您是否同时替换了 :selected 选项时间?
然后:selected => @course.tod_like 在选择标签中?
Is the params key correct?
I take it the form f is for an instance of Course so wouldn't it be something like
@course.tod_like = params[:search][:tod_like] ? params[:search][:tod_like] : ""
at the top of the function that generates the search function (you have mentioned that you've tried a ternary statement but did you replace the :selected option at the same time?
Then :selected => @course.tod_like in the select tag?
嗯,我最终通过在课程控制器中定义三元运算符,然后将此实例变量传递到适当的视图中来解决这个问题。
此代码与我之前尝试的三元运算符之间的主要区别在于,我正在测试 params[:search] 是否为 nil,而不是 params[:search][:tod_like] 是否为 nil。由于 params[:search] 已经为零,当我尝试使用 params[:search][:tod_like] 时,我得到了“you were waiting an array,but getting nil”错误。
感谢您的回复!
Hmm, I ended up fixing this problem by defining a ternary operator in my courses controller, and then passing this instance variable into the appropriate view.
The key difference between this code and the previous ternary operator I tried is that I'm testing to see if params[:search] is nil, not if params[:search][:tod_like] is nil. Since params[:search] is already nil, I got the "you were expecting an array, but got nil" error when I tried to use params[:search][:tod_like].
Thanks for your responses!