n:mのmodel定義
has_many through:を使う
- モデル定義
rails g model User name:string
rails g model Project name:string
rails g model UserProjectGroup user_id:integer project_id:integer
rake db:migrate
modelに追記
class User < ActiveRecord::Base
has_many :user_project_groups
has_many :projects, through: :user_project_groups
end
class Project < ActiveRecord::Base
has_many :user_project_groups
has_many :users, through: :user_project_groups
end
class UserProjectGroup < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
・コントローラ
rails g controller user_project
class UserProjectController < ApplicationController
def relate
user1 = User.create(name: “ichiro”)
user2 = User.create(name: “jiro”)
px = Project.create(name: “X”)
pa = Project.create(name: “A”)
user1.projects << pa #関連づけ
user2.projects << pa
user1.projects << px
user2.projects << px
render json: UserProjectGroup.all
end
def ichiro
user1 = User.find_by_name(“ichiro”)
render json: user1.projects
end
def jiro
user2 = User.find_by_name(“jiro”)
render json: user2.projects
end
end
- ルーティング
get ‘relate’ => ‘user_project#relate’
get ‘ichiro’ => ‘user_project#ichiro’
get ‘jiro’ => ‘user_project#jiro’