Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails &引用;属性应该是散列,但却是字符串;_Ruby On Rails_Ruby On Rails 3_Hash - Fatal编程技术网

Ruby on rails &引用;属性应该是散列,但却是字符串;

Ruby on rails &引用;属性应该是散列,但却是字符串;,ruby-on-rails,ruby-on-rails-3,hash,Ruby On Rails,Ruby On Rails 3,Hash,我在Rails 3应用程序中保存哈希时遇到问题。当我使用控制台时,我可以保存它-当我通过表单提交哈希时,它就是不起作用 但解决方案对我不起作用。此外,如果我使用: serialize :bulk_action, Hash 我得到一个错误: Attribute was supposed to be a Hash, but was a String 通过表单保存时,哈希如下所示: "{\"location\"=>{\"commands\"=>{\"custom_command_

我在Rails 3应用程序中保存哈希时遇到问题。当我使用控制台时,我可以保存它-当我通过表单提交哈希时,它就是不起作用

但解决方案对我不起作用。此外,如果我使用:

 serialize :bulk_action, Hash
我得到一个错误:

 Attribute was supposed to be a Hash, but was a String
通过表单保存时,哈希如下所示:

 "{\"location\"=>{\"commands\"=>{\"custom_command_one\"=>\"true\", \"custom_command_two\"=>\"true\"}}}"
鉴于,通过控制台:

{"location"=>{"commands"=>{"custom_command_one"=>"true", "custom_command_two"=>"true"}}}
我的数据库字段是一个文本字段。通过表单保存哈希的最佳方法是什么

--编辑--


我发现,如果我使用符号而不是字符串作为名称,但它仍然输出一个长字符串,而不是散列,我可以在某种程度上绕过这个问题。

你能在文本区域内切换到JSON,这样解析就不会那么危险了。因为您必须要做的是评估控制器或模型中相应的参数条目,以便用户可以对运行应用程序的用户执行任何操作。对于JSON,您可以在设置model属性之前使用
JSON.parse

我也没有找到正确的答案(YAML.dump,to_YAML-Rails 4.0.1中的相同错误)。只有eval能帮我。这不是一个大的安全问题,因为我在管理窗格中使用它

  params[:branch][:features_attributes][:primary] = eval params[:branch][:features_attributes][:primary]
  params[:branch][:features_attributes][:secondary] = eval params[:branch][:features_attributes][:secondary]
  if @branch.update_attributes(params[:branch]) ...        
从链接

因此,该列应包含批量操作的YAMLized版本,但'

 "{\"location\"=>{\"commands\"=>{\"custom_command_one\"=>\"true\", \"custom_command_two\"=>\"true\"}}}"
不是YAML哈希。如果您想处理原始序列化数据,那么应该使用

 "{\"location\"=>{\"commands\"=>{\"custom_command_one\"=>\"true\", \"custom_command_two\"=>\"true\"}}}".to_yaml

我最近也遇到过这种错误。引发行动的链条是:

  • 具有可序列化字段的模型
    数据
  • 该字段必须存在(模型验证+数据库约束)
  • 由于db约束
    NOT NULL
    生成矩阵中的sqlite db适配器失败,因为它不能在
    NOT NULL
    受限字段上允许默认值
    NULL
  • 由于sqlite,空字符串被设置为字段的默认值:
    default:“
  • 在初始化新模型时,当我们在rails4上升级时,它被预设为
    instance.data='
  • 但是保存此模型失败,错误消息
    “属性应该是散列,但却是字符串”
    ,因为没有任何内容覆盖此错误字段值
解决方案:
-添加一个迁移,使用:
change\u列:model,:data,:text,default:'-{}'
作为有效的可序列化空默认值

您使用什么表单标记输入哈希:input,textarea@莫里茨尝试了文本区域和文本输入,但没有成功。我想知道是不是haml在做什么,但这似乎有些牵强。我甚至在MySql中切换到blob类型。我只是在尝试。当您说切换到JSON时,您的意思是在保存/更新之前解析控制器中的字段吗。例如:params[:payload]=JSON.parse(params[:payload])我想我可以删除这个字段。并手动输入。它只为超级管理员设计,而不是为最终用户设计的。。。。
 "{\"location\"=>{\"commands\"=>{\"custom_command_one\"=>\"true\", \"custom_command_two\"=>\"true\"}}}".to_yaml