Rails has_many:通过未初始化的常量

时间:2015-09-12 01:31:39

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

我正在寻找帮助调试Rails has_many的问题:通过关联。我有3个模型,套餐地点,以及我的联接表,套餐优惠

package.rb

class Package < ActiveRecord::Base
    has_many :packagevenues
    has_many :venues, through: :packagevenues
end

venue.rb

class Venue < ActiveRecord::Base
    has_many :packagevenues
    has_many :packages, through: :packagevenues
end

packagevenue.rb

class Packagevenue < ActiveRecord::Base
    belongs_to :venues
    belongs_to :packages
end

packagevenues表的架构

 create_table "packagevenues", force: :cascade do |t|
    t.integer  "package_id"
    t.integer  "venue_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

测试用例:

  Packagevenue.first
  Packagevenue Load (0.3ms)  SELECT  "packagevenues".* FROM "packagevenues"  ORDER BY "packagevenues"."id" ASC LIMIT 1
=> #<Packagevenue:0x007fac12209750> {
          :id => 1,
  :package_id => 2,
    :venue_id => 1,
.....
}   

[11] webapp »  p=Package.find(2)
  Package Load (0.2ms)  SELECT  "packages".* FROM "packages" WHERE "packages"."id" = $1 LIMIT 1  [["id", 2]]
=> #<Package:0x007fac14eae738> {
          :id => 2,
.....
}

[12] webapp »  v=Venue.find(1)
  Venue Load (0.2ms)  SELECT  "venues".* FROM "venues" WHERE "venues"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Venue:0x007fac1222e488> {
           :id => 1,
.....
}

[13] webapp »  v.packages
NameError: uninitialized constant Venue::Packages
.....

[14] webapp »  p.venues
NameError: uninitialized constant Package::Venues
.....

我以为我正确地完成了所有设置,有人可以让我知道为什么未初始化的常量错误会不断出现?

1 个答案:

答案 0 :(得分:9)

可能的原因是belongs_to模型中的多个Packagevenue符号。你希望那些像这样的单数:

class Packagevenue < ActiveRecord::Base
    belongs_to :venue
    belongs_to :package
end