NameError - 具有多态关联的未初始化常量

时间:2014-10-03 22:19:30

标签: ruby-on-rails

我有两个模型如下:

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

我可以通过控制台保存这种关系:

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

但是,当我通过表单提交尝试时,我收到以下错误:

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'

这是控制器和表格:

@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 %>

提交给服务器的内容(我使用...删除不必要的内容):

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

我过去曾使用fields_for来使用多态关系。所以我不确定这里发生了什么。

1 个答案:

答案 0 :(得分:1)

FullcalendarEngine::Event课程中,您的belongs_to应声明如下:

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

'::'强制const查找发生在名称空间的根目录而不是当前名称空间内。