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