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
end
# in models/user.rb
class User < ActiveRecord::Base
has_one :pet
accepts_nested_attributes_for :pet
end
# in admin/user.rb
ActiveAdmin.register User do
permit_params :name, :age, pet_attributes: [:id, :name] # NB the id parameter..
end
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, f.object.pet || Pet.new] do |pet| %>
<%= pet.input :name %>
<% end %>
<% end %>
view raw has_one hosted with ❤ by GitHub

The hack in particular is f.object.pet || Pet.new. (With many thanks to simonc!)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s