LoginSignup
29
22

More than 5 years have passed since last update.

Railsのルーティングでid(主キー)を変更する

Last updated at Posted at 2015-05-24

はじめに

Railsでbookモデルを作ると、booksテーブルの各bookのidは数字の主キーが自動的に振り分けられ、対象のbookへのアクセスには以下のようなURLが使われる。

http://localhost:3000/books/1

ところで、このid(主キー)の部分を変えたい。

とりあえずレコードの内容

"id":"1"
"isbn":"978-4167413019"
"title":"落語と私"
"author":"桂米朝"
"published_at":"1986/03"
"created_at":"2015-05-24T08:48:02.255Z"
"updated_at":"2015-05-24T08:48:02.255Z"

ここでは、isbnを主キーにすることにする。

Bookモデルで主キーを設定

app>models>book.rb
class Book < ActiveRecord::Base
  self.primary_key = "isbn"
end

すると...

http://localhost:3000/books/978-4167413019

-> アクセスできた。

"id":"978-4167413019"
"isbn":"978-4167413019"
"title":"落語と私"
"author":"桂米朝"
"published_at":"1986/03"
"created_at":"2015-05-24T08:48:02.255Z"
"updated_at":"2015-05-24T08:48:02.255Z"

-> レコードの内容はこう。
-> idの部分にisbnと同じ内容が振られていた。

http://localhost:3000/books/978-4167413019/edit

-> これもOK
-> destroyもOK
-> おわり

まとめ

あっちこっちと紆余曲折したわりには、なんとモデルに1行加えるだけで終わってしまった。

追記(15/5/28)

プライマリーキーを変えたのはいいけれど、bookテーブルにbelongs_toでアソシエーションされたreviewモデルは、外部キーbook_idをinteger型でとっているので、そのままだとわけのわからないことになってしまった。

そこで、schema.rbを書き換えて、book_idをstring型で取れるようにした。

schema.rb
  create_table "books", force: :cascade do |t|
    t.string   "isbn"
    t.string   "title" 
    t.integer  "author"
    t.string   "published_at"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

  create_table "reviews", force: :cascade do |t|
    t.string   "comment"
    t.string   "book_id" # 外部キー。元々はt.integer
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

これでうまくアソシエーションしてくれた。

29
22
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
29
22