【问题标题】:Activerecord in rails 3.2 within an engine throws NameError: uninitialized constant when using accepts_nested_attributes_for引擎中的 Rails 3.2 中的 Activerecord 抛出 NameError: uninitialized constant when using accepted_nested_attributes_for
【发布时间】:2012-06-13 05:11:51
【问题描述】:

我正在构建一个 Rails 引擎。我有以下两个模型类:

module LandingPageEng
    class LandingPage < ActiveRecord::Base
        attr_protected # just for debugging right now
        has_many :slide_show_images, :dependent => :destroy
        accepts_nested_attributes_for :slide_show_images, allow_destroy: true
    end
end

第二类是:

module LandingPageEng
    class SlideShowImage < ActiveRecord::Base
        attr_accessible :image, :landing_page_id
        belongs_to :landing_page 

        validates :image, :presence => true
    end
end

与它们关联的表格是landing_page_eng_landing_page 和landing_page_eng_slide_show_image。

当我在控制台中运行以下命令时,我收到错误 NameError: uninitialized constant SlideShowImage。

1.9.3-p194 :001 > LandingPageEng::LandingPage.new({"title"=>"wd", "tagline"=>"wed",     "slide_show_images"=>{"_destroy"=>""}})
NameError: uninitialized constant SlideShowImage
    from /Users/martinjlogan/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-  3.2.6/lib/active_support/inflector/methods.rb:229:in `block in constantize'
    from /Users/martinjlogan/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.6/lib/active_support/inflector/methods.rb:228:in `each'
    from /Users/martinjlogan/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.6/lib/active_support/inflector/methods.rb:228:in `constantize'
    from /Users/martinjlogan/.rvm/gems/ruby-1.9.3-p194/gems/activesupport-3.2.6/lib/active_support/core_ext/string/inflections.rb:54:in `constantize'
<snip>

我一直在努力解决这个问题,但无法弄清楚。非常感谢任何帮助。

【问题讨论】:

    标签: ruby activerecord ruby-on-rails-3.2 rails-engines


    【解决方案1】:

    我没有带有引擎的 Rails 3 设置来快速测试它,但我认为问题在于您的 has_many 配置;它正在寻找一个名为 SlideShowImage 但你的类名为 LandingPageEng::SlideShowImage 的类。

    我相信在您的has_many 中添加:class_name 选项可以解决此问题。

    http://railsapi.com/doc/rails-v3.0.8rc1/classes/ActiveRecord/Associations/ClassMethods.html#M004956

    【讨论】:

    • 感谢您帮助 Ryan。现在我得到了一些相当奇怪的东西。现在似乎期望我使用 :class_name 指定的类,而是找到一个 Array?? ActiveRecord::AssociationTypeMismatch: LandingPageEng::SlideShowImage(#70200876366100) expected, got Array(#70200871589540)
    • 看起来传入的参数有问题。不是将 slide_show_image_attributes 作为键传递,而是从表单传递 slide_show_images 。相同的代码在引擎之外运行良好。虽然这是进步。谢谢。
    • 似乎是多个变量同时变化的问题。不知道我做了什么。现在一切正常,您的解决方案是正确的。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多