LoginSignup
40
45

More than 5 years have passed since last update.

Railsで既存のテーブルをModelとして使用する

Last updated at Posted at 2013-04-12
$rails g model hogehoge 

で空のModelを作成する。
作成されたModelのset_table_nameを指定する。

hogehoge.rb
class Hogehoge < ActiveRecord::Base
  set_table_name :hogehoge
end

こうすると、既存のテーブル定義をそもままModelとして使用できる。
また対象のテーブルのPKがID以外であった場合は、さらにset_primary_keyを使用する。

hogehoge.rb
class Hogehoge < ActiveRecord::Base
  set_table_name :hogehoge 
  set_primary_key :hogeid
end

PKをID以外のものに指定した場合は、Model.find の引数もIDではなく、PKの値を取るようになる。

> hogeid = Hogehoge.find("hogeid")
40
45
3

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
40
45