LoginSignup
9
8

More than 5 years have passed since last update.

ActiveRecordで多対多の関係を定義する

Last updated at Posted at 2014-05-30

”学生”と”授業”の関係を例にとる。

もし、"学生"と"授業"の関連に対してなんらかのパラメータを持たせたい場合(例えば授業の評価とか)は
has_many :throughで関係を定義したほうが良い。

#学生モデル
class Students < ActiveRecord::Base
  has_many :takes
  #takesという中間テーブルを介してlessonsと関連している
  has_many :lessons, :through => :takes
end
#受講モデル 受講という関連をモデル化
class takes < ActiveRecord::Base
  belongs_to :student
  belongs_to :lesson
end
#授業モデル
class Lessons < ActiveRecord::Base
  has_many :students
  #takesという中間テーブルを介してstudentsと関連している
  has_many :students, :through => :takes
end

ER図風AAで書くと
students --< takes >-- lessons

"学生"と”授業”の関連だけが表せればよいという場合は、has_many_belongs_toで定義すればよいだろう。

class Students < ActiveRecord::Base
  has_many_and_belongs_to :lessons
end
class Lessons < ActiveRecord::Base
  has_many_and_belongs_to :students
end

ER図風AAで表すと
students --< users_lessons >-- lessons

詳細は、Ruby on Railsの公式ドキュメントを参照のこと
http://guides.rubyonrails.org/association_basics.html

ググるワード
rails model association

9
8
2

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
9
8