Rails:NameError:未初始化的常量OrderItem

时间:2015-09-28 08:24:36

标签: ruby-on-rails ruby ruby-on-rails-4

模型/ order_item.rb

class OrderItem < ActiveRecord::Base    
  belongs_to :item
  belongs_to :order 
  belongs_to :user
end

模型/ order.rb

 class Order < ActiveRecord::Base   
     has_many :order_item
 end

现在,我使用rails console测试它们。当我输入OrderItem时,它会抛出

NameError: uninitialized constant OrderItem

更新

我在rails console

中这样做了
2.1.3 :021 >   reload!
Reloading...
 => true 
2.1.3 :022 > Order
 => Order(id: integer, user_id: integer, created_at: datetime, updated_at: datetime, status: integer) 
2.1.3 :023 > Item
 => Item(id: integer, status: integer, name: string, price: integer, descript: text, created_at: datetime, updated_at: datetime, cover_file_name: string, cover_content_type: string, cover_file_size: integer, cover_updated_at: datetime, cate_id: integer) 
2.1.3 :024 > User
 => User(id: integer, email: string, encrypted_password: string, created_at: datetime, updated_at: datetime) 
2.1.3 :025 > OrderItem
NameError: uninitialized constant OrderItem
    from (irb):25
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/railties-4.2.3/lib/rails/commands/console.rb:110:in `start'
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/railties-4.2.3/lib/rails/commands/console.rb:9:in `start'
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/railties-4.2.3/lib/rails/commands.rb:17:in `<top (required)>'
    from /Users/Coda/Desktop/code/ruby_pra/shop/bin/rails:8:in `<top (required)>'
    from /Users/Coda/.rvm/rubies/ruby-2.1.3/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Users/Coda/.rvm/rubies/ruby-2.1.3/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from -e:1:in `<main>'

2 个答案:

答案 0 :(得分:4)

  

NameError:未初始化的常量OrderItem

has_many 关联名称 应为plural,因此has_many :order_item更改为has_many :order_items order.rb 1}}

#order.rb
class Order < ActiveRecord::Base   
  has_many :order_items #plural
end

<强> 更新

github 上查看代码,order_item.rb之间有一个 空间 ,即( {strong> 文件名order_item .rb)中的app/models/order_item .rb)。将其更改为order_item.rb

答案 1 :(得分:1)

根据评论,并删除任何疑问,这是我对代码的期望:

#app/models/order.rb
class Order < ActiveRecord::Base
   belongs_to :user #-> the order belongs to user, so if order_items belong to order, they belong to user, right?
   has_many :order_items
   has_many :items, through: :order_items
end

#app/models/order_item.rb
class OrderItem < ActiveRecord::Base
  #table name "order_items"
  #columns id | item_id | order_id | created_at | updated_at
  belongs_to :item
  belongs_to :order 
end

这是一种典型的has_many :through关系,因为我相信你已经知道了。

-

使用Pavan的更新答案;上面的内容应该可以让您了解模型所需的代码类型。