I finally got this to work with Rails 4.x. This is based on Dmitry / Scott's answer, therefore +1 to them.
STEP 1. To get started, here is a complete model with polymorphic association:
# app/models/polymorph.rb class Polymorph < ActiveRecord::Base belongs_to :associable, polymorphic: true accepts_nested_attributes_for :associable def build_associable(params) self.associable = associable_type.constantize.new(params) end end
Yes, this is nothing new. However, you may wonder where polymorph_type comes from and how is its value set? This is part of the database entry because polymorphic associations add the columns <association_name>_id and <association_name>_type . However, when build_associable is executed, the value of _type is nil .
STEP 2. Skip and accept the type of child
Submit the form in the child_type form along with typical form data, and your controller should enable it when checking strong parameters.
# app/views/polymorph/_form.html.erb <%= form_for(@polymorph) do |form| %> # Pass in the child_type - This one has been turned into a chicken! <%= form.hidden_field(:polymorph_type, value: 'Chicken' %> ... # Form values for Chicken <%= form.fields_for(:chicken) do |chicken_form| %> <%= chicken_form.text_field(:hunger_level) %> <%= chicken_form.text_field(:poop_level) %> ...etc... <% end %> <% end %> # app/controllers/polymorph_controllers.erb ... private def polymorph_params params.require(:polymorph).permit(:id, :polymorph_id, :polymorph_type) end
Of course, your views will have to handle the various types of models that are βrelatedβ, but this demonstrates one.
Hope this helps someone. (Why do you need polymorphic chickens?)
rodamn Oct 02 '15 at 20:29 2015-10-02 20:29
source share