Creating a nested attributes form for polymorphic/single table inheritance associations

Andrew Havens
Mon, 01 Jul 2013 20:27:56 -0000

I am working on a form (using SimpleForm) that allows you to edit embedded
associations. The problem that I''m running into is that the nested
models
are subclasses so they are different types with potentially different
fields. I''m creating hidden forms for each type of model, and using
JavaScript to display the form for the selected type. I''m using Mongoid
and
SimpleForm, but I expect the implementation would be the same using
ActiveRecord and the standard Rails form helpers.

Here''s a simplified example of what I have so far:

class Garage
  include Mongoid::Document
  embeds_one :vehicle
  accepts_nested_attributes_for :vehicleend
class Vehicle
  include Mongoid::Document
  embedded_in :garage
  attr_accessible :_typeend
class Car < Vehicle
  field :car_field
  attr_accessible :car_fieldend
class Truck < Vehicle
  field :truck_field
  attr_accessible :truck_fieldend

In the console:

> garage = Garage.new> garage.vehicle = Car.new(car_field:
''something'')> garage.save!

In the form:

= simple_form_for @garage do |f|
  = f.input :vehicle do |vehicle_form|
     = vehicle_form.input :_type, collection: [''Car'',
''Truck'']

  %span.hide{data:{fields-for:''Car''}}
    = vehicle_form.input :car_field

  %span.hide{data:{fields-for:''Truck''}}
    = vehicle_form.input :truck_field
:coffeescript
  $(''#garage_vehicle_attributes__type'').change ->
    type = $(@).find(''option:selected'').val()
    $(''[data-fields-for="'' + type +
''"]'').show()

The problem that will occur in this example is that it won''t be able to
render the truck_field becauseCar does not have a truck_field method.
I''m
not sure how to solve this problem besides throwing out any form helpers
and managing the html and field values manually. Even after much Googling,
I haven''t been able to find any examples of this type of form.

How can this problem be solved in a standard, "Rails way" using
existing
form helpers?

Any tips or advice you can give would be greatly appreciated. Thanks!

--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/d20bdf7b-214f-4260-ba6c-3a8903c5a414%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.