user1666543
user1666543

Reputation: 685

uninitialized constant but the table exists

I am sure its a basic problem in RoR but I added a new table called hooods_one_providers. This table has no corresponding model - It should connects two models - Providers and Hoods. I am trying to call it in the console but getting instead - uninitialized constant.

When I run:

ActiveRecord::Base.connection.tables
=> ["schema_migrations", "users", "roles", "users_roles", "providers", "food_items", "food_items_users", "feedbacks", "addresses", "carts", "link_carts", "hoods", "drink_items", "addons_ons", "addons_nears", "customize_foods", "addresses_hoods", "hoods_one_providers"]

I can see the table but I cant read from it. When I run hooods_one_providers i get the uninitialized constant error:

NameError: uninitialized constant HoodsOneProvider
    from (irb):14
    from /home/ido/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
    from /home/ido/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
    from /home/ido/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

In the model provider I have:

has_and_belongs_to_many :hoods_one, class_name: 'HoodsOne'

And in the model hood I have:

has_and_belongs_to_many :providers

Will appreciate any help. Thanks

Upvotes: 2

Views: 2556

Answers (2)

Abdul Basit Mangat
Abdul Basit Mangat

Reputation: 1180

This could happen for any one of the cases below

  1. Running reload! should fix.
  2. Exit the console and run console again by rails c
  3. Make sure the model file exists for the respective table. Let's assume your table name is hoods_one_providers then there should be hoods_one_providers.rb file under the model.

Upvotes: 4

jvnill
jvnill

Reputation: 29599

if you've added the table while the console is running, the classes are already cached by the console. Running reload! should fix the issue but in case it doesn't, a restart of the console should.

UPDATE:

You are using has_and_belongs_to_many which needs you to manually create the joins table.

UPDATE: creating the joins table

create a migration which contains the following to create the joins table. the id: false option tells it not to create an id column

create_table :hoods_ones_providers, id: false do |t|
  t.references :hoods_one, :provider
end

add_index :hoods_ones_providers, [:hoods_one_id, :provider_id]

Upvotes: 1

Related Questions