0

I'm having issue creating a nested polymorphic form. I am following the solution from this problem:

Rails: has_many through with polymorphic association - will this work?

The description was: A Person can have many Events and each Event can have one polymorphic Eventable record

Here are the relevant models:

class Event < ActiveRecord::Base
  belongs_to :person
  belongs_to :eventable, :polymorphic => true
end

class Meal < ActiveRecord::Base
  has_one :event, :as => eventable
end

class Workout < ActiveRecord::Base
  has_one :event, :as => eventable
end

class Person < ActiveRecord::Base
  has_many :events
  has_many :meals, :through => :events, :source => :eventable,
    :source_type => "Meal"
  has_many :workouts, :through => :events, :source => :eventable,
    :source_type => "Workout"
end

My controller looks like this:

def 
  @person = Person.new
  @person.meals.new
  @person.workouts.new
new

My view looks like this:

<%=  form_for @person do |person| %>
 <%= person.fields_for :meals, @person.meals.build do |meals| %>
   <%= meals.text_field :food %>
  <% end %>
<% end %>

The error I am currently getting is:

unknown attribute: person_id

I would think that the polymorphic association is hindering the creation of the object because meals can't be create until person has been created? Did I set up the form correctly? Thanks!

Community
  • 1
  • 1
guy8214
  • 1,115
  • 2
  • 12
  • 14

1 Answers1

0

You'll need to include a person_id attribute in the events table (as per the belongs_to association)

There are also some other issues you should resolve:


Controller

def new
    @person = Person.build
end

def create
    @person = Person.new(person_attributes)
    @person.save
end

private

def person_attributes
    params.require(:person).permit(:your, :attributes, events_attributes: [:eventable_type, :eventable_id, meal_attributes: [:params], workout_attributes: [:params]])
end

Models

#app/models/person.rb
Class Person < ActiveRecord::Base
    has_many :events
    has_many :meals, :through => :events, :source => :eventable,
        :source_type => "Meal"
    has_many :workouts, :through => :events, :source => :eventable,
        :source_type => "Workout"

    def self.build
        person = Person.new
        person.events.build.build_meal
        person.events.build.build_workout
    end

end

Views

#app/views/people/new.html.erb
<%=  form_for @person do |person| %>
 <%= person.fields_for :events do |e| %>
   <%= e.fields_for :meal %>
       <%= e.text_field :food %>
   <% end %>
  <% end %>
<% end %>
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • Thanks for the answer Rich. Now I'm getting a unknown attribute: eventable_id. Is this because events is the polymorphic connection and needs to know Meal's id before it can create itself? – guy8214 Feb 04 '14 at 16:26