Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_many :through Uninitialized constant

I'm looking for help debugging an issue with a Rails has_many :through association. I have 3 models, Package, Venue, and my join table, Packagevenue

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

schema for packagevenues table

 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

Test Case:

  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
.....

I thought I did all of the setup correctly, can somebody please let me know why the Uninitialized Constant error keeps popping up?

like image 707
tomtom Avatar asked Dec 24 '22 14:12

tomtom


1 Answers

The likely cause is due to the plurality of the belongs_to symbols in your Packagevenue model. You want those to be singular like so:

class Packagevenue < ActiveRecord::Base
    belongs_to :venue
    belongs_to :package
end
like image 133
Marc Baumbach Avatar answered Jan 04 '23 18:01

Marc Baumbach