LoginSignup
90
91

More than 5 years have passed since last update.

Railsでhas_and_belongs_to_manyのモデルを作成する

Last updated at Posted at 2014-10-09

このような関係を作成するときの手順です。

hbtm_erd.PNG

まずはモデルとマイグレーションを作成。

$ rails g model user name:string email:string
$ rails g model group name:string description:text
$ rails g migration create_groups_users group:references user:references

create_groups_usersのところはテーブル名をアルファベット順でつなぐ。

中間テーブルはidカラムを作成しないようにするため、以下のようにマイグレーションファイルを編集します。

class CreateGroupsUsers < ActiveRecord::Migration
  def change
    create_table :groups_users, id: false do |t|
      t.references :group, index: true, null: false
      t.references :user, index: true, null: false
    end
  end
end
  1. create_table()の引数に id: false を追加
  2. t.references の引数に null: false を追加

これでマイグレーション実行。

$ rake db:migrate:reset

で、モデルにアソシエーション設定を記述。

app/models/user.rb
class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
end
app/models/group.rb
class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
end

使えるようになるメソッド

has_and_belongs_to_many - リファレンス - Railsドキュメント

使い方の例

whereメソッドでの絞り込み

グループID:1に所属するユーザーを取得。

User.includes(:groups).where('groups.id' => 1)

配列でも指定できる。

User.includes(:groups).where('groups.id' => [1, 2])

ユーザーにグループを関連付ける

new_user = User.new(:name => 'newuser', email => 'newuser@example.com')
new_user.groups << Group.find(1)
new_user.save

コントローラー/ビューからの使い方

記事を追加しました。
Railsでhas_and_belongs_to_manyを利用したUIを作成する

90
91
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
90
91