Nazar Hussain
Nazar Hussain

Reputation: 5162

Generate form from a Hash in Rails 3

I need to generate a form from a hash and get it back its posted params in a hash. for this, i created this class.

class Hashit
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def initialize(hash)
    hash.each do |k, v|
      self.class.send(:attr_accessor, k.to_sym)
      if v.class.name == "ActiveSupport::HashWithIndifferentAccess"
        self.send("#{k}=", Hashit.new(v))
      else
        self.send("#{k}=", v)
      end
    end
  end
  def persisted?
    true
  end
end

now for example i have a settings hash. {:live=>{:title=>"Live Title"}, :staging=>{:title=>'Staging Title'}} convert it to an object with @settings_obj = Hashit.new(settings) and then used simple_form to generate form for it.

 <%= simple_form_for @settings_obj, :url => app_settings_url do |f| %>
     <%= f.fields_for :live do |l| %>
         <%= l.input :title %>
     <% end %>
     <%= f.fields_for :staging do |s| %>
         <%= s.input :title %>
     <% end %>
     <%= f.submit %>
 <% end %>

The form is generated properly with proper field names, but only issue is the fields do not have values in them.

How to solve this issue?

Upvotes: 1

Views: 532

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

With fields_for you have to tell it what the form build should bind to (except in the case of accepts_nested_attributes_for which is a whole different kettle of fish), i.e. do something like

<%= f.fields_for :live, f.object.live do |l|%>

You might be able to get away with

<%= f.fields_for f.object.live %>

But only if fields for can extract the name 'live' from the object which i don't think it can do in your case since the ActiveModel naming stuff is conceptually a class level thing, not an instance thing.

Upvotes: 2

Related Questions