0

The models BarberShop (table barber_shops) and Barber (table barbers) all exist. In rails c after

x = Barber.new and x.include? :barbershop => true. 

So the association should be set up correctly. When I try to save I get the

Name error Uninitialized constant BarberShop::Barber.

I know it is something more than likely easy that I am having trouble finding. For example I learned today with a has-many-through-association the order (in the model) of the associations matter where a must be listed to get b - i.e.

has_many :a 
has_many :b, through: :a

The models are as below -

Barber < ApplicationRecord
  belongs_to :barbershop
  has_many :appointments 
  has_many :customers, through: :appointments


BarberShop < ApplicationRecord 
    has_many :barbers
end 
#schema in db
create_table "barber_shops", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "barbers", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.integer "barbershop_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["barbershop_id"], name: "index_barbers_on_barbershop_id"
  end

Shiny
  • 4,945
  • 3
  • 17
  • 33
rTaylor
  • 39
  • 5
  • updated table still does not work ```class create_table :barbers do |t| t.string :name t.references :barbershop ``` – rTaylor Jan 20 '20 at 21:18
  • Where is the code you are using to save? – hashrocket Jan 21 '20 at 04:32
  • ```> x => # > x.save BarberShop Create (3.0ms) INSERT INTO "barber_shops" commit transaction => true 2.6.1 :006 > x => # 2.6.1 :007 > y 2.6.1 :008 > y.barbershop_id = 2 => 2 2.6.1 :009 > y => # 2.6.1 :010 > y.save NameError (uninitialized constant Barber::Barbershop): 2::11 1::11:in `rescue in irb_binding' NameError (uninitialized constant Barber::Barbershop) > y.barbershop_id => 2``` – rTaylor Jan 21 '20 at 12:41
  • if above is TL;DR status ```y.save Traceback (most recent call last): 1: from (irb):17 NameError (uninitialized constant Barber::Barbershop)``` where y is a barber.new with a name and barbershop_id. This error is unusual to me. I don't know what to do and i believe it is how my associations are established. I could be incorrect. – rTaylor Jan 21 '20 at 12:43
  • Does this answer your question? [Ruby on rails: Creating a model entry with a belongs\_to association](https://stackoverflow.com/questions/16286944/ruby-on-rails-creating-a-model-entry-with-a-belongs-to-association) – Int'l Man Of Coding Mystery Jan 21 '20 at 13:47

1 Answers1

0

In a Rails app, the model BarberShop needs to be in the file app/models/barber_shop.rb and the model Barber needs to be in the file app/model/barber.rb.

If you don't name the files correctly, you can get odd behaviour because objects don't autoload as they should.

ReggieB
  • 8,100
  • 3
  • 38
  • 46