0
请参考代码。如何将text_fields映射到Rails 3中的哈希对象字段?
<%= form_tag(:action => "create_user", :method => "post") do%>
<p><label for="first_name">First Name</label>:
<%= text_field 'json_parsed', 'first_name') %></p>
<p><label for="middle_name">Middle Name</label>:
<%= text_field 'json_parsed', 'middle_name') %></p>
<p><label for="last_name">Last Name</label>:
<%= text_field 'json_parsed', 'last_name') %></p>
<% @contact = @json_parsed["contact"] %>
<p><label for="last_name">Email</label>:
<%= text_field 'contact','email']) %></p>
<p><label for="last_name">Phone</label>:
<%= text_field 'contact', 'phone_no') %></p>
<%= submit_tag "Create" %>
<% end %>
这里, 'json_parsed
' 那就是我曾json_decode
后得到了哈希对象。 first_name/middle_name/etc
。是该散列对象中的所有字段。现在我想要在text_field中获取这些值。但它给错误“未定义的方法”first_name
'为散列“。
我怎样才能显示这些值散列直接到text_field?
看到我的哈希对象这样使用它包含: {“FIRST_NAME” =>“Aashish”,“middle_name”=>“Shrikant”,“last_name”=>“Pathak”,“contact”=> {“email”=>“[email protected]”,“phone_no”=>“9922582272 “},”profile“=> {age} =>”22“,”ht“=>”175“,”wt“=>”67“}} 我试过像你说的那样将它转换为类对象。但它给错误'未定义的方法[] Hashit' – Aashish 2011-03-02 09:15:22
如果你看到的哈希对象,它是嵌套的。基本上这是我从一个web服务获得的。现在我想发送同样的结构回其他一些web服务来保存新数据。 – Aashish 2011-03-02 09:18:38
你应该编辑你的'%@contact = @json_parsed [“contact”]%>'line to'<%@contact = @ json_parsed.contact]%>'并且使用'fields_for'进行联系。我会编辑我的答案。 – rubyprince 2011-03-02 09:22:20