【问题标题】:Rails4 fields_for and serialized hash. Got 'TypeError: expected Hash (got String)'Rails4 fields_for 和序列化哈希。得到'TypeError:预期的哈希(得到字符串)'
【发布时间】:2013-10-03 18:31:09
【问题描述】:

我已经序列化了Product的属性属性

class Product < ActiveRecord::Base
  serialize :properties, Hash

产品表 (sqlite3) 的文本列“属性”包含以下内容:

---
:article: shirt
:size: L
:color: red

当我从控制台检索产品的属性时,我会获得一个哈希值,我可以毫无问题地对其进行修改和保存。 Ruby 完美地对其进行序列化和反序列化。 然后我尝试使用 fields_for 为每个属性构建一个带有一个 text_field 的 _form.html.erb:

<%= form_for(@product) do |f| %>
[....]
  <div class="field">
    <%= f.fields_for :properties, OpenStruct.new(@product.properties) do |property_form| %>
      <%= f.label :properties %><br />
      <% @product.properties.keys.each do |k| %>
        <%= property_form.label k %><br />
        <%= property_form.text_field k, :value => @product.properties[k] %>
      <% end %>
    <% end %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

当我编辑一个产品时,这段代码创建了 3 个填充了正确值的 text_fields,但是当我尝试保存它时,我得到:

"ERROR TypeError: 参数'properties'的预期哈希(得到字符串)"

怎么了?我已经阅读了很多类似问题的一些解决方案,我遵循了不同的方法,如thisRailscast#403 中的建议,但我总是陷入这种错误。我可能错过了一些东西,但我找不到什么。任何想法? (ruby-2.0.0-p247,Rails 4.0.0)

非常感谢!

【问题讨论】:

    标签: ruby-on-rails ruby serialization hash ruby-on-rails-4


    【解决方案1】:

    由于我陷入困境并需要快速解决方案,因此我使用了一种简单的解决方法:我为每个 text_field 创建了一个变量“property_n”,并在保存对象之前将其复制到哈希中。 现在编辑表单是这样的:

    <% for i in 0..max_num_of_properties %>
      <div class="field">
        <%= f.label "property_#{i}".to_sym %><br>
        <%= f.text_field "property_#{i}".to_sym %>
      </div>
    <% end %>
    

    产品类是:

    class Product < ActiveRecord::Base
      serialize :properties, Hash
    
      before_save do
        self.properties = {}
        property_names = ProductType.find(product_type_id).get_property_names()
        property_names.each_with_index do |name, index|
          self.properties[name] = get_property(index)
        end
      end
    
      def get_property(index)
        send("property_#{index}")
      end
    

    哈希现在可以完美地序列化。通过一些 JS 行,我在编辑表单中显示了正确的属性数量和名称(来自 ProductType)。 我知道这不是完美的解决方案,但它可能对某人有用...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2022-06-15
      相关资源
      最近更新 更多