How to set up form for a hash in Rails?

纵然是瞬间 提交于 2019-12-03 07:26:23
nemesv

Based on this article you should change the name in text_field_tag to

<% @hash.keys.each do |key| %>
  <div class="field">
    <%= f.label key %><br />
    <%= text_field_tag "hash[" + key + "]", @hash[key] %> 
  </div>
<% end %>

My answer is not strictly on topic but I really recommend you to take a look at http://railscasts.com/episodes/219-active-model. You could use ActiveModel APIs to simulate a model object with Rails 3. Doing that you could simply do something like

<%= form_for(@object) %>

and leaving the populating of your object to Rails APIs.

When you use the helpers that end with _tag that's what happens.

Instead of text_field_tag ... use f.text_field ....

In order to get a hash like params => {:hash => {:field1 => "", :field2 => ""}} you have to pair up form_for with f.input_field_type instead of simply input_field_tag.

See the difference?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!