简体   繁体   中英

Ruby on rails from console - (Table doesn't exist)

I'm learning RoR in Windows 7 with InstantRails.

I got into sqlite3 successfully and created a table named Trades with a handful of columns. I got out of that and into ruby console.

>> class Trade < ActiveRecord::Base; end
=> nil
>> trade = Trade.new
=> #<Trade barterID: nil, title: nil, message: nil, created_at: nil, updated_at: nil>
>> trade.class
=> Trade(Table doesn't exist)

I double-checked that by getting back into sqlite3 and it's definitely there. I know the table isn't named "Trade" so I tried re-naming is as Trade, but it gave even more errors. I read that the table name should be in plural format, so I think I have that part right.

Any help on why it says the table doesn't exist? I'll give any details I haven't thought of.

rails g model Trade will give you a correct template, but if you just want to fix your migration file, please make sure you create this table: trades (plural not singular) .

Rails will give you (Table doesn't exist) error if you have trade(singular) table in the database. I think the error is kinds of misleading.

In Rails, you have to do a total abstraction of your DB. Whatever you work with sqlite or mysql the steps are the same (except the first configuraion, but sqlite doesn't need).

The normal process is the following :

  1. Generate a Model with rails generator

    rails generate model Trade

  2. Edit the associated migration file, (something like 2012xxxxxxxx_create_trades.rb in db/migrate/ ) and put it the schema of Trade. syntax here

  3. Run rake db:migrate in order to apply the changes to the database

  4. Use your Model

Did you create the table manually ? If so, it isn't the "Rails way" of creating tables/models. You should use a rails Generator :

rails g model Trade

The generator will create a model class in app/models and a migration file in the db/migrate directory. Then, add the db columns using the migration DSL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM