【问题标题】:Rails refers to wrong model on create with nested modelsRails 在使用嵌套模型创建时引用了错误的模型
【发布时间】:2018-04-27 16:54:24
【问题描述】:

我有一个名为Foo 的模型和一个名为Foo::Type 的嵌套模型。我想创建一个新的Foo,其foo_type_id 为42。我可以调用Foo.new(foo_type_id: 42),但是当我尝试调用#save 时,我收到错误Uninitialized constant Foo::FooType。我如何才能向 Rails 澄清我的意思?

我的模型文件夹如下所示(连字符表示文件):

models
  - foo.rb
    foo
      - type.rb

我的Foo::Type 模型是空的,而我的Foo 模型只是belongs_to :foo_type

重现步骤

rails new sampleapp
cd sampleapp
rails g model foo/type name:text
rails g model foo foo_type:references
rails db:migrate
rails c # The next steps should be in IRB
Foo::Type.create(name: 'Test Type')
Foo.new(foo_type_id: 1).save

【问题讨论】:

    标签: ruby-on-rails model nested rails-activerecord


    【解决方案1】:

    您是Foo 模型需要知道foo_type 指的是Foo::Type,而不是默认假设FooType。为此,在您的Foo 模型中,当您设置belongs_to 关系时,您需要说belongs_to :foo_type, class_name: "Foo::Type"。这告诉Foo 如何找到Foo::Type 模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 2012-11-04
      • 2017-07-28
      • 1970-01-01
      • 2014-10-24
      • 2020-08-25
      相关资源
      最近更新 更多