Red > Green > Refactor > Red

cycle is based on desire

many to many(関連) ; Rails ; Design

多対多を実現するには中間モデルが必要(当事者モデル2つだけでなく)

フレームワーク思想に則って現れたらしく。

この経緯に付いては(分かっていないことが多いので)省略。

Prepare

$ rails g model Member name:string
$ rails g model Article title:string
$ rails g model ArticlesMember article_id:integer member_id:integer
$ rake db:migrate

app/models/member.rb

class Member
  has_many :articles_members
  has_many :articles, through: :articles_members
end

app/models/article.rb

class Article
  has_many :articles_members
  has_many :articles, through: articles_members
end

app/models/member.rb

class Member
  belongs_to :article
  belongs_to :member
end

db/seeds.rb

Member.create! do |member|
  member.name = 'mat5ukawa'
end

Member.create! do |member|
  member.name = 'awaku5tam'
end
rake db:seed

action on rails c

$ rails c

> member = Member.find(1)
>> #<Member id: 1,
             name: "mat5ukawa",
             created_at: "2014-01-28 13:04:42",
             updated_at: "2014-01-28 13:04:42">

> member.articles
>>  #<ActiveRecord::Associations::CollectionProxy []>

> member.articles.create(title: 'Maybe Im a leo')
>> begin transaction
>> commit transaction
>> => #<Article id: 2,
                title: "Maybe Im a leo",
                created_at: "2014-01-28 13:35:47",
                updated_at: "2014-01-28 13:35:47">

> member.articles.create(title: 'Smoke on the water')
>> begin transaction
>> commit transaction
>> => #<Article id: 3,
                title: "Smoke on the water",
                created_at: "2014-01-28 13:37:41",
                updated_at: "2014-01-28 13:37:41">

> member.articles
>> => #<ActiveRecord::Associations::CollectionProxy
  [#<Article id: 2,
             title: "Maybe Im a leo",
             created_at: "2014-01-28 13:35:47",
             updated_at: "2014-01-28 13:35:47">,
   #<Article id: 3,
             title: "Smoke on the water",
             created_at: "2014-01-28 13:37:41",
             updated_at: "2014-01-28 13:37:41">]>

> article = Article.find(2)
>> #<Article id: 2,
             title: "Maybe Im a leo",
             created_at: "2014-01-28 13:35:47",
             updated_at: "2014-01-28 13:35:47">

> article.members.create(name: 'mat7ukawa')
>> begin transaction
>> commit transaction
>> #<Member id: 3,
            name: "mat7ukawa",
            created_at: "2014-01-28 13:42:13",
            updated_at: "2014-01-28 13:42:13">

> article.members
>> #<ActiveRecord::Associations::CollectionProxy
  [#<Member id: 1,
            name: "mat5ukawa",
            created_at: "2014-01-28 13:31:44",
            updated_at: "2014-01-28 13:31:44">,
   #<Member id: 3,
             name: "mat7ukawa",
             created_at: "2014-01-28 13:42:13",
             updated_at: "2014-01-28 13:42:13">]>

参考元 # ありがとうございます

soraなりの日々 - fc2 - [ruby, rails]今更だが、has_many :through(多対多)をまとめてみよーか