How to set up form for a hash in Rails?

15,750

Solution 1

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 %>

Solution 2

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.

Share:
15,750
B Seven
Author by

B Seven

Status: Hood Rails on HTTP/2: Rails HTTP/2 Rack Gems: Rack Crud Rack Routing Capybara Jasmine

Updated on June 08, 2022

Comments

  • B Seven
    B Seven almost 2 years

    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 with 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.

  • m_x
    m_x over 12 years
    agreed, but maybe this hash is a symptom of bad practice. Asked him for more precision.
  • m_x
    m_x over 12 years
  • B Seven
    B Seven over 12 years
    Interesting. I'm not sure if that approach will work because this code is actually inside of a form generated for a model.
  • lucapette
    lucapette over 12 years
    Then you could try to use to use a fields_for... to be honest I haven't tried it but I don't see any particular problem.