如何将text_fields映射到Rails 3中的Hash对象字段?

时间:2011-03-02 06:32:09

标签: ruby-on-rails ruby ruby-on-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中?

1 个答案:

答案 0 :(得分:1)

您不能将text_field用于哈希对象。它可以用于模型对象(具有您调用的名称的方法的对象,例如。@json_parsed应该有一个方法first_name,以便我们可以调用@json_parsed.first_name)。对于哈希,我们不能这样称呼它。所以,你应该像这样使用text_field_tag

<%=text_field_tag 'json_parsed[first_name]', :value => @json_parsed["first_name"]%> 

或者您应该使用Hashit将哈希值转换为具有相应方法名称的ruby类对象。

class Hashit
  def initialize(hash)
    hash.each do |k,v|
      v = Hashit.new(v) if v.is_a?(Hash)
      self.instance_variable_set("@#{k}", v) ## create and initialize an instance variable for this key/value pair
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")}) ## create the getter that returns the instance variable
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)}) ## create the setter that sets the instance variable
    end
  end
end

并使用它来制作对象,

@json_parsed = Hashit.new(json_parsed_hash)

并在视图中使用它。有关Hashit的更多详细信息,请参阅此link

对于您的联系人哈希,您应该像这样使用它

<p><label for="last_name">Email</label>:
<%= fields_for @json_parsed.contact do |p|%
    <%= p.text_field 'email'%></p>
<p><label for="last_name">Phone</label>:
    <%= p.text_field 'phone_no') %></p>

也许,您应该在视图中使用它

<% form_for :json_parsed, :url => {:action => "create_user"} do |f| %>
<p><label for="first_name">First Name</label>:
    <%= f.text_field 'first_name' %></p>
<p><label for="middle_name">Middle Name</label>:
    <%= f.text_field 'middle_name' %></p>
<p><label for="last_name">Last Name</label>:
    <%= f.text_field 'last_name' %></p>
    <% f.fields_for 'contact' do |p| %>
<p><label for="last_name">Email</label>:
    <%= p.text_field 'email' %></p>
<p><label for="last_name">Phone</label>:
    <%= p.text_field 'phone_no' %></p>
<% end %>
<%= submit_tag "Create" %>
<% end %>