0

Say I have the following polymorphic association:

class EmailAddress < ActiveRecord::Base
  belongs_to :emailable, polymorphic: true
end

class Person < ActiveRecord::Base
  has_many :email_addresses, as: :emailable, dependent: :destroy
  accepts_nested_attributes_for :email_addresses
end

class Organization < ActiveRecord::Base
  has_many :email_addresses, as: :emailable, dependent: :destroy
  accepts_nested_attributes_for :email_addresses
end

I'm using the nested_form gem to help build a dynamic nested form where multiple email addresses can be added/removed when editing a person or organization. Ryan's documentation (modified for this example) states that if you use <%= f.fields_for :email_addresses %> then "it will look for a partial called "email_address_fields" and pass the form builder as an f variable to it."

This is handy, but in my case the email address fields partials would be exactly the same for both people and organizations. Instead of having both /app/views/people/_email_address_fields.html.erb and /app/views/organizations/_email_address_fields.html.erb, is there a way to tell the f.fields_for method to use a different partial (e.g., one created in /app/views/email_addresses/_fields.html/erb or something similar)?

I thought of the following:

<%= f.fields_for :email_addresses do |email_address_form| %>
  <%= render partial: 'email_addresses/fields', locals: { f: email_address_form } %>
<% end %>

Is there a better way though?

robertwbradford
  • 6,181
  • 9
  • 36
  • 61

1 Answers1

1

No, I don't believe there is a better way, although you could make a helper method to remove duplication if you really want to. We use exactly the same strategy for nested link forms:

<%= f.fields_for :links do |link_form| %>
  <%= render partial: "shared/link_fields", locals: { f: link_form } %>
<% end %>
jvperrin
  • 3,368
  • 1
  • 23
  • 33