模型中检测名称空间不正确

时间:2014-03-17 13:33:24

标签: ruby-on-rails activerecord rspec ruby-on-rails-4 model

我有一个简单的模型

class Order < ActiveRecord::Base
    has_many :products, dependent: :destroy, class_name: 'Order::Product'
    has_many :attributes, dependent: :destroy, class_name: 'Order::Attribute'
    belongs_to :customer
    has_one :invoice_address, class_name: 'Order::Address'
    has_one :delivery_address, class_name: 'Order::Address'

    validates :number, presence: true
    validates :total_amount, presence: true
end

我想向订单添加产品和属性。我创建了2个新文件 模型/订单/ product.rb

class Order::Product < ActiveRecord::Base
    belongs_to :order
end

和models / order / attribute.rb

class Order::Attribute < ActiveRecord::Base
    belongs_to :order
end

我用代码创建了种子文件:

dev_customer = Customer.create(:name => 'dev')

first_order = dev_customer.orders.create(:total_amount => 555, :paid_amount => 555)

first_order.products.create(:name => 'First product', :price => 111, :qty => 1)
first_order.products.create(:name => 'Second product', :price => 222, :qty => 2)
but when I execute rake db:setup I receive error
  

除非保存父级,否则无法调用create

第5行。我做错了什么?

在rspec测试中,我收到了不同的错误

$ rspec
/home/bartek/.rvm/gems/ruby-2.1.1/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:464:in `load_missing_constant': Unable to autoload constant Product, expected /home/bartek/rails_apps/allemag/app/models/order/product.rb to define it (LoadError)

这是我的config / application.rb文件

require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)

module Allemag
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
    config.autoload_paths += %W(#{config.root}/lib)
    config.i18n.enforce_available_locales = true
  end
end

我做错了什么?我认为rails存在命名空间问题,但不知道如何解决它。我正在使用rails4。

1 个答案:

答案 0 :(得分:0)

您在rspec中加载模型时遇到错误,因为未正确定义模块“Order”。您可以按如下方式更改Order类的声明,以修复类加载问题:

module Order
  class Product < ActiveRecord::Base
    belongs_to :order
  end
end

当您定义包含模块的类名时,此使用模块,但如果模块不存在则不定义模块。明确声明模块然后在其中声明类将定义模块并在该命名空间中添加Class。