Reputation: 2479
I have an existing remote mysql database and I am trying to access that from my rails application I have this in my database.yml development:
development:
adapter: mysql2
encoding: utf8
database: mydb
username: myusername
password: !@#$%@!
host: IP for my DB
port: 3306
pool: 5
socket: /tmp/mysql.sock
timeout: 5000
when I run the following the command in my rails console
ActiveRecord::Base.connection.tables
It list all the available tables but when I try to access the model it gives me the following error:
City
NameError: uninitialized constant City from (irb):12
from /home/shreyas/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
from /home/shreyas/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
from /home/shreyas/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Any suggestions what I am doing wrong ? I want to access the remote database in my application I havent created any models as of now. Do I need to create all the models? I can see the complete db structure in my schema.rb file.
Upvotes: 4
Views: 2347
Reputation: 1109
In case anyone comes across this, make sure to double check your models. I created them manually and forgot to allow Active Record to be aware of my models.
I had:
class Currency
...
end
you need to change this to show
class Currency < ApplicationRecord
...
end
Might save you hours of debugging :)
Upvotes: 1
Reputation: 5734
For that in console you can write the code like
rails g model City
it will create the City model for you. As you said, you have existing table, so you don't need the migration generated by the above syntax. So you should delete the generated migration from db/migrate.
OR else you can do one thing just add city.rb file in the app/models. Then add the code
class City < ActiveRecord::Base
# if your table name is cities, then you don't need to do any thing.
# if your table name is something else rather than cities then place the following commented code
# self.table_name = 'your_existing_city_table_name'
# then you have to add columns of the table as attr_accessible. for e.g. you have name, state_id in there
attr_accessible :name, :state_id
end
Hope it will work for you :)
Upvotes: 5
Reputation: 17631
You can of course access your data inside your mysql
database but in order to use it as an object representation you need to create a model
associated with your data.
class City < ActiveRecord::Base
end
This way ActiveRecord
will do the hard work for you in order to "link" your object to the data in your database (assuming the models name are correct, here you should have a table named cities
).
You will then be able to fetch cities from rails console
City.all
For more informations on ActiveRecord, please refer to http://guides.rubyonrails.org/active_record_querying.html
Upvotes: 0