rails ActiveAdmin nested form has_one accepts_attributes_for formtastic issue

thrice801 picture thrice801 · Nov 16, 2011 · Viewed 17.8k times · Source

I am using ActiveAdmin and Rails 3.1 -- having problem understanding whether the following is a bug, or if there is some way to do it correctly that I am not understanding. I am trying to use a nested model with a has one relationship, so that I can create a page and fill out it's meta data in 1 step. -- (page has_one meta_data, accepts_nested_attributes_for meta_data)

Example 1) in this example, when I click new page, meta data section is there but there are no input fields -- also, if I edit the record, it shows up correctly, however the fieldset is duplicated in the second section... and if I remove the f.inputs wrapping semantic_field_for (which would make sense), then it breaks completely and shows nothing in the meta data area...

form do |f|
  f.inputs "Page Information" do
    f.input :name
    f.input :uri
    f.input :view
    f.input :body, :as => :text
    f.input :active
  end

  f.inputs "Meta Data" do
    f.semantic_fields_for :meta_data do |meta_form|
      meta_form.inputs :title, :description, :keywords, :name => "Meta Information"
    end
  end  
end

I understand the meta data probably isn't being instantiated, but I am not sure how I am supposed to do that in the form block? (or if I can even do it) -- The only way I am able to get this to work is by doing using a custom form, and building the meta data in the view, which looks like this

2) How I am working around it, but seems hacky

<%= semantic_form_for [:admin, @page] do |f| %>
  <% @page.build_meta_data %>
  <%= f.inputs :name => "Page Information" do  %>
    <%= f.input :name %>
    <%= f.input :uri %>
    <%= f.input :view %>
    <%= f.input :body, :as => :text %>
    <%= f.input :active %>
  <% end %>
  <%= f.semantic_fields_for :meta_data do |meta_form| %>
    <%= meta_form.inputs :title, :description, :keywords, :name => "Meta Information" %>
  <% end %>

  <%= f.buttons %>
<% end %>

Thanks in advance for any help or clarification.

(note to moderators I started another thread on this but was not as clear and didn't have the workaround solution I do now yet, so if one of the questions should be deleted please delete the other)

Answer

Pechkin picture Pechkin · Jan 7, 2012

I found a better solution for you. You can use :for option in inputs helper.

f.inputs "Meta Data", for: [:meta_data, f.object.meta_data || MetaData.new] do |meta_form|
  meta_form.input :title
  meta_form.input :description
  meta_form.input :keywords
end

I think this might work too, but I didn't check

f.inputs :title, :desctiption, :keywords, 
  name: "Meta Data",
  for: [:meta_data, f.object.meta_data || MetaData.new]