ruby-on-rails - 访问视图中的哈希时Rails未定义的方法
问题描述
在编辑操作下,我在绘图控制器中定义了一个哈希
@custom_params = { :custom_plot_type => "Line", :x_axis_title => "", :x_low => "", :x_high => "", :y_axis_title => "", :y_low => "", :y_high => "" }
当我访问编辑页面时,我有一个 form_with @plot 作为模型,其中包含以下选择框:
= fields_for :custom_params do |c|
= c.label(':custom_plot_type', "Plot Type")
= c.select(:custom_plot_type, options_for_select(['Line', 'Scatter', 'Heat Map', 'Column'], @custom_params[:custom_plot_type]))
Rails 给了我以下错误
#< Hash:0x00007ffff8c4b030> 的未定义方法“custom_plot_type”
我已经按照这个问题的答案,我很确定我对哈希的定义是正确的。但无论我以哪种方式格式化它(例如,使用"custom_plot_type" => "Line"
and@custom_params["custom_plot_type"]
代替)我都会在视图中得到相同的错误。
我也可以在控制器的控制台中输出我想要的元素,使用
puts @custom_params
puts @custom_params[:custom_plot_type]
这会输出正确的值,但是一旦我尝试在视图中访问它,它就会崩溃
编辑:添加有关表单的更多信息以澄清以回应评论。我的表格结构如下:
= form_with(model: @plot, local: true, method: "patch") do |f|
= label_tag('plot[name]', "New plot name:")
= text_field_tag('plot[name]', @plot.name)
%br
= label_tag('plot[description]', "Description:")
= text_field_tag('plot[description]', @plot.description)
%br
%br
= fields_for :custom_params do |c|
= c.label(':custom_plot_type', "Plot Type")
= c.select(:custom_plot_type, options_for_select(['Line', 'Scatter', 'Heat Map', 'Column'], @custom_params[:custom_plot_type]))
这背后的想法是拥有一个具有与 Plot 模型相关联的字段的表单,并且还有一个用于“自定义参数”的子表单,这些子表单与模型本身无关,但将保存到文件中。所以表单确实有一个与之关联的模型实例,但有问题的选择标签没有。
解决方案
我编辑了表单以使用 aselect_tag
而不是c.select
元素,如下所示:
= fields_for :custom_params do |c|
= label_tag('custom_params[:custom_plot_type]', "Plot Type")
= select_tag('custom_params[:custom_plot_type]', options_for_select(['Line', 'Scatter', 'Heat Map', 'Column'], @custom_params[:custom_plot_type]))
稍后我仍然将 c 的值用于其他表单元素,但是使用 _tag 元素而不是与表单构建器相关的元素允许我在选择标记中使用任意散列 - 感谢@tgmerritt 的建议
推荐阅读
- sql - 引用第二个表的新列 - 我需要加入吗?
- mysql - 其中包含 STR_TO_DATE 和 SUBSTRING
- python - 获取 jupyter notebook 以打印它已导入的整个函数
- javascript - React.js 表单 - 如何在最后一页包含所有值?
- mysql - 执行此 INSERT 语句时,我应该更改什么以避免 Aurora MySQL 错误 1034?
- python - 无法读取正确的 buildozer logcat
- node.js - 反应,节点:变量在 app.post() 上显示未定义
- javascript - ajax, jquery with mysql query in js - 这可能吗?
- javascript - $.get 返回相同的数组
- node.js - 未使用 REST API 在 Node Js 中调用函数