Ruby on Railsでの多対多の関連付け

背景 自分は現在院生2回生で, 4回生のころから京都のゲーム・Web会社で働いている. 今も細々と続けている中で, Ruby on Railsに触れる機会があったのでその知見を貯めておく. 今回は多対多の関連付けと, その使い方を紹介する. データ構造 このアプリケーションには, userとgroupの定義があって, userは複数のgroupに所属することができて, groupは複数のuserを持つ. よって中間テーブルを用いて多対多の関連付けを定義する. schema.rb ActiveRecord::Schema.define(version: 20_190_219_052_352) do create_table "group_users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.bigint "user_id", null: false t.bigint "group_id", null: false t.index ["group_id"], name: "index_group_users_on_group_id" t.index %w[user_id group_id], name: "index_group_users_on_user_id_and_group_id" t.index ["user_id"], name: "index_group_users_on_user_id" end create_table "groups", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "name", null: false t.integer "status", default: 1, null: false end create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "name", null: false end end テーブル名をgroup_usersにして中間テーブルを作る. このテーブルをもとにgroupからuser, userからgroupを参照する. ここでindexが3つ貼られているが, 以下のようにして簡単に貼ることができる. create_group_users.rb class CreateGroupUsers < ActiveRecord::Migration[5.2] def change create_table :group_users do |t| t.references :user, null: false, foreign_key: true t.references :group, null: false, foreign_key: true t.timestamps end add_index :group_users, %i[user_id group_id] end end 関連付け 以下がそれぞれのモデルである. ...

April 12, 2019 · 2 min

Ruby on Railsでオシャレな処理を書く

背景 自分は現在院生2回生で, 4回生のころから京都のゲーム・Web会社で働いている. 今も細々と続けている中で, Ruby on Railsに触れる機会があったのでその知見を貯めておく. また, Ruby on Railsは型が決まった書き方があるので, 少ない行数に多くの情報を詰め込むことができて, 書き終わった後の見通しがとてもいいと思う. そんなオシャレな書き方を少し紹介したい. 使用するデータのスキーマとモデル 今回紹介するのは, SNSアプリのAPIの中身の一部である. 以下に, 端末の情報を持つdeviceテーブルと, ユーザーの情報をもつuserテーブルを定義する. schema.rb ActiveRecord::Schema.define(version: 20_190_219_052_352) do create_table "devices", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.bigint "user_id" t.string "uuid" t.integer "user_agent" end create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| t.string "email", null: false t.string "password_digest", null: false end end ```ruby `user`と`device`の関係は1対多であり, `belongs_to`と`has_many`で関連付けされている. 以下にそれぞれもモデルを示す. user.rb ```ruby class User < ApplicationRecord has_many :devices, dependent: :nullify end Device.rb class Device < ApplicationRecord belongs_to :user, optional: true # deviceとuser_idを紐づける def update_user_id(user) user.devices << self end def shape_response { uuid: uuid } end end オシャレな文法たち 上記データ構造をもとにおしゃれな文法たちを紹介する. ...

April 12, 2019 · 2 min