LoginSignup
52
54

More than 5 years have passed since last update.

[Rails]既存のMySQLテーブルに接続する方法

Last updated at Posted at 2014-01-30

別のアプリケーションで使っていたテーブルをRailsでデータ引っ張ってきたい時の方法。
※Rails4.0.2 Ruby2.0.0で確認

Railsでプロジェクト作って。。。

rails new アプリケーション名

MySQLに接続はいつもどおりのmysql2

gem 'mysql2'
database.yml
development:
  adapter: mysql2
  encoding: utf8
  database: database
  username: name
  password: pass
  host: localhost
  port: 3306
  pool: 5
  timeout: 5000

とりあえず$ bundle install後に$ rails sで起動確認しておく

こっから本番。
schema.rbにMySQLのテーブル情報を書き込みたいので、

$ rake environment -v -t RAILS_ENV=development db:schema:dump

とする。
そうすると、schema.rbにMySQLのテーブル情報が書き込まれていることが確認できます。

その後、モデルを作成。
作成したモデルと標準のテーブル名が違う場合は、

test.rb
class Test < ActiveRecord::Base
  self.table_name = "test"

end

とすると、testsというようなテーブル名じゃなくてもデータを取得できます。

test_controller.rb
def test
    test = Test.where(["name = ?", "hoge"])
    p test
end

こんな感じ。

52
54
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
54