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?