Donato
Donato

Reputation: 2777

NameError - uninitialized constant with polymorphic association

I have two models as follows:

module FullcalendarEngine
  class Event < ActiveRecord::Base
    belongs_to :profile, polymorphic: :true
    accepts_nested_attributes_for :profile
  end
end

class UserProfile < ActiveRecord::Base
    has_many :fullcalendar_engine_events, as: :profile, class_name: 'FullcalendarEngine::Event'
end

I can save this relation through the console:

l = UserProfile.first
e = l.fullcalendar_engine_events.build
e.save!

However, when I try it through a form submission, I get the following error:

NameError - uninitialized constant FullcalendarEngine::Event::Profile:
  activerecord (4.1.5) lib/active_record/inheritance.rb:133:in `compute_type'
  activerecord (4.1.5) lib/active_record/reflection.rb:221:in `klass'
  activerecord (4.1.5) lib/active_record/nested_attributes.rb:545:in `raise_nested_attributes_record_not_found!'
  activerecord (4.1.5) lib/active_record/nested_attributes.rb:387:in `assign_nested_attributes_for_one_to_one_association'
  activerecord (4.1.5) lib/active_record/nested_attributes.rb:343:in `profile_attributes='
  activerecord (4.1.5) lib/active_record/attribute_assignment.rb:45:in `public_send'
  activerecord (4.1.5) lib/active_record/attribute_assignment.rb:45:in `_assign_attribute'
  activerecord (4.1.5) lib/active_record/attribute_assignment.rb:56:in `block in assign_nested_parameter_attributes'
  activerecord (4.1.5) lib/active_record/attribute_assignment.rb:56:in `each'
  activerecord (4.1.5) lib/active_record/attribute_assignment.rb:56:in `assign_nested_parameter_attributes'
  activerecord (4.1.5) lib/active_record/attribute_assignment.rb:36:in `assign_attributes'
  activerecord (4.1.5) lib/active_record/core.rb:455:in `init_attributes'
  activerecord (4.1.5) lib/active_record/core.rb:198:in `initialize'
  activerecord (4.1.5) lib/active_record/inheritance.rb:30:in `new'
  activerecord (4.1.5) lib/active_record/inheritance.rb:30:in `new'

This is the controller and form:

@profile = Profile.find(params[:profile])
@event = @profile.fullcalendar_engine_events.build

<%= form_for @event %>
      <%= f.fields_for :profile, @profile do |builder| %>
          <%= builder.hidden_field :id %>
      <% end %>
<% end %>

What's submitted to server (I use ... to remove unncessary stuff):

Parameters: { ... "event"=>{ ... , "profile_attributes"=>{"id"=>"2"}}}

I've used polymorphic relations in the past with fields_for. So I am not sure what's going on here.

Upvotes: 1

Views: 1400

Answers (1)

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

At the FullcalendarEngine::Event class, your belongs_to should be declared like this:

belongs_to :profile, polymorphic: :true, class_name: "::Profile"

The '::' forces the const lookup to happen from the root of the namespaces instead of inside the current namespace.

Upvotes: 1

Related Questions