开发者

How to set up form for a hash in Rails?

开发者 https://www.devze.com 2023-04-06 16:11 出处:网络
I have some data associated with a model that is in a hash. The hash is generated in the controller: @hash.

I have some data associated with a model that is in a hash. The hash is generated in the controller: @hash.

What is the proper way to create a form for this data?

I came up with the following code for the view:

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

This generates the form, but it creates each hash item as a separate variable in the form. This doesn't seem to be the proper way to submit the data back. I would like to get the data back as a hash, and access it wi开发者_StackOverflow中文版th params[:hash].

What is the best way to do this?

Working in Rails 3.07, Ruby 1.9.2.

Thanks.

EDIT: I should have made this clear. This code is inside of a form generated for a model. So, the form needs to submit all the fields for the model, plus the above hash.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号