【发布时间】:2014-03-17 13:33:24
【问题描述】:
我有一个简单的模型
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 个新文件 models/order/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。
【问题讨论】:
-
如果从配置中删除自动加载路径是否有效? Rails 应该能够从类名推断模型文件名。确保您始终使用命名空间版本——“产品”不应单独出现。
-
我测试了您的解决方案,但在 rspec 测试中收到错误
uninitialized constant Order::Order::Attribute -
如果您显示测试代码可能会有所帮助。
标签: ruby-on-rails activerecord rspec ruby-on-rails-4 model