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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With