Reputation: 1093
I'm following the book: "Rails, Angular, Postgres and Bootstrap". At some point, the author wrote a new migration, with this code:
class AddAddresses < ActiveRecord::Migration
def change
create_table :states do |t|
t.string :code, size: 2, null: false
t.string :name, null: false
end
create_table :addresses do |t|
t.string :street, null: false
t.string :city, null: false
t.references :state, null: false
t.string :zipcode, null: false
end
create_table :customers_billing_addresses do |t|
t.references :customer, null: false
t.references :address, null: false
end
create_table :customers_shipping_addresses do |t|
t.references :customer, null: false
t.references :address, null: false
t.boolean :primary, null: false, default: false
end
end
end
Here is what I did:
rails g migration add-addresses
Copied and pasted the code above in the generated migration-file
rake db:migrate
This happens:
== 20161211174928 AddAddresses: migrating =====================================
-- create_table(:states)
-> 0.0140s
-- create_table(:addresses)
-> 0.0129s
-- create_table(:customers_billing_addresses)
-> 0.0115s
-- create_table(:customers_shipping_addresses)
-> 0.0142s
== 20161211174928 AddAddresses: migrated (0.0529s) ============================
rails c
State.last
causes this:
NameError: uninitialized constant State
I checked, whether 'State' was around:
ActiveRecord::Base.connection.tables.map do |model|
model.capitalize.singularize.camelize
end
leads to:
["SchemaMigration", "ArInternalMetadatum", "User", "Customer", "State", "Address", "CustomersBillingAddress", "CustomersShippingAddress"]
Since 'State' is clearly there, I'm clueless what the problem is. Any suggestions?
PS: I already tried this, but the problem remains:
rake db:drop:all
rake db:create:all
rake db:migrate
Upvotes: 1
Views: 2770
Reputation: 694
Since you indicate State.code and State.name cannot be blank, and very likely do not have any data in the table, start by creating some data, i.e.:
state = State.create(code: 12, name: "New Jersey")
Make a file called state.rb in the models directory. in it put:
class State < ActiveRecord::Base
end
and see if that works. Later you can add the associations. This will initialize the class.
Upvotes: 0
Reputation: 11915
Do you have a state.rb
file under app/models
directory? I guess you don't. Creating a table will not generate the model
(class) while generating the model using rails g model
will create the migration for you.
Create a file called state.rb
in app/models
and add the following contents to the file.
class State < ActiveRecord::Base
end
Upvotes: 2