LoginSignup
17
18

More than 3 years have passed since last update.

RailsのDB設計

Last updated at Posted at 2016-12-26

一年間Railsを書いてきたので、Railsの設計の仕方をざっと書きます。

設計

自分が見ていたインターン生がやってしまった失敗を
元に書いてみます。

  • db設計

webアプリケーションにおいて、DB設計はかなり重要になります。
Railsが用いるORMはActiveRecordですが、基本はRDBを使用します。
なのでRDBの理解する必要があります。

これは他人が設計した例ですが、タグの設計をすると
タグはこれかも増えてくいくとします。
投稿の postsと タグをtagsとすると

1つの投稿に複数のタグをつけたいため
下記のようなschemaを作ったとします。

create_table "posts", force: :cascade do |t|
  t.integer  "user_id",    limit: 4
  t.datetime "created_at",             null: false
  t.datetime "updated_at",             null: false
end

create_table "tags", force: :cascade do |t|
 t.integer  "post_id"
 t.boolean  "food"
 t.boolean  "fashion"
 t.boolean  "music"
 t.boolean  "culture"
 t.boolean  "travel"
 t.boolean  "other"
 t.datetime "created_at",             null: false
 t.datetime "updated_at",             null: false
end

こうすると、

Post.find(1).tags

とすれば
論理値でtagの確認出来る分けです。

でもカラムが多いだけパラメータが増えたり
クエリも書きにくくなります。
タグを増やすたびにスキーマ変更しなければならず
タグから投稿を探すのも大変なのです。

これを正規化すると解決します。

投稿とタグの間に中間テーブルをおきます。

そしてタグテーブルの
レコードにfoodfashionなどを保存します。

create_table "posts", force: :cascade do |t|
  t.integer  "user_id",    limit: 4
  t.datetime "created_at",             null: false
  t.datetime "updated_at",             null: false
end


create_table "tags_posts", force: :cascade do |t|
 t.integer  "post_id"
 t.string   "tag_id"
 t.datetime "created_at",             null: false
 t.datetime "updated_at",             null: false
end

create_table "tags", force: :cascade do |t|
 t.string   "name"
 t.datetime "created_at",             null: false
 t.datetime "updated_at",             null: false
end

こうしてあげることで

Post.find(1).tags

というクエリを書くと、
postが持っているtagだけが表示されるようになります。
もちろん

Tag.find(1).posts

とすると
Tagに紐付いている投稿の情報を得ることができます。

17
18
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
17
18