formtastic and has_one relationship: workaround

I’ve implemented many belongs_to and has_many relationships via ActiveAdmin and formtastic, but never a has_one relationship. I found a quick fix via this git issue.

Let’s take a simple example: we have users and each user “has_one” pet. The ActiveAdmin setup is similar to other relationships.

# in models/pet.rb
class Pet < ActiveRecord::Base
# in models/user.rb
class User < ActiveRecord::Base
has_one :pet
accepts_nested_attributes_for :pet
# in admin/user.rb
ActiveAdmin.register User do
permit_params :name, :age, pet_attributes: [:id, :name] # NB the id parameter..
view raw gistfile1.rb hosted with ❤ by GitHub

And this is the setup for our formtastic nested form

<%= semantic_nested_form_for [:admin, @user], :html => {:multipart => true} do |f| %>
<%= f.inputs 'User Information' do %>
<%= f.input :name %>
<%= f.input :age %>
<% end %>
<%= f.inputs 'User's Pet' for: [:pet, ||] do |pet| %>
<%= pet.input :name %>
<% end %>
<% end %>
view raw has_one hosted with ❤ by GitHub

The hack in particular is || (With many thanks to simonc!)