Red > Green > Refactor > Red

cycle is based on desire

one to many(関連) ; Rails ; Design

1 対 多 on Rails

モデルを使ったとき、どのようにして実現するか

Student - Subject 関連を使う

Prepare

$ rails g model Student name:string
$ rails g model Subject name:string student:references
$ rake db:migrate

db/seeds.rb

Student.create! do |student|
  student.name = 'mat5ukawa'
end

$ rake db:seed

app/models/student.rb

class Student
  has_many :subjects
end

app/models/subject.rb class Subject belongs_to :student end

rails c でアクション確認

$ rails c
> student = Student.find(1)
>> => #<Student id: 1,
                 name: 'ma5ukawa',
                 created_at: "2014-01-27 14:14:58",
                 updated_at: "2014-01-27 14:14:58">

> student.subjects
>> #<ActiveRecord::Associations::CollectionProxy []>

> student.subjects.create(name: 'math')
>> begin transaction
>> INSERT INTO "subjects" ...
>> commit transaction

> Subject.find(1)
>>  => #<Subject id: 1,
                  name: "math",
                  student_id: 1,
                  created_at: "2014-01-27 14:28:53",
                  updated_at: "2014-01-27 14:28:53">

> student.subjects
>> => #<ActiveRecord::Associations::CollectionProxy
      [#<Subject id: 1,
                 name: "math",
                 student_id: 1,
                 created_at: "2014-01-27 14:28:53",
                 updated_at: "2014-01-27 14:28:53">]> 

> student.subjects.create(name: 'physics')
>> begin transaction
>> commit transaction

> student.subjects
>> => #<ActiveRecord::Associations::CollectionProxy
     [#<Subject id: 1,
                name: "math",
                student_id: 1,
                created_at: "2014-01-27 14:28:53",
                updated_at: "2014-01-27 14:28:53">,
      #<Subject id: 2,
                name: "physics",
                student_id: 1,
                created_at: "2014-01-27 14:34:23",
                updated_at: "2014-01-27 14:34:23">]>

参考元 # thanks

has_many (ActiveRecord::Associations::ClassMethods) - APIdock