Red > Green > Refactor > Red

cycle is based on desire

one to one(関連) ; Rails ; Design

Rails 書留レベル

one to one をどうやって実現するか

Subject - Page 関連

generate model

$ rails g model Subject name:string
$ rails g model page name:string subject:references
$ rake db:migrate

app/models/subject.rb

class Subject
  has_one :page
end

app/models/page.rb

class Page
  belongs_to :subject, foreign_key: :subject_id
end

db/seeds.rb

Subject.create! do |subject|
  subject.name = 'math'
end
$ rake db:seed

(一部簡略化)

$ rails c
> sub = Subject.find(1)
>> => #<Subject id: 1,
                name: "math",
                created_at: "2014-01-26 16:05:03",
                updated_at: "2014-01-26 16:05:03">

> sub.page
>> => nil

> first_page = Page.new(name: 'first_page')
>> => #<Page id: nil, name: "first_page",
             subject_id: nil,
             created_at: nil,
             updated_at: nil>>

> first_page.subject
>> => nil

> sub.page = first_page
>> begin transaction
>> INSERT INTO "pages" ("created_at", "name", "subject_id", "updated_at")
   VALUES (?, ?, ?, ?)  [["created_at", Sun, 26 Jan 2014 16:22:05 UTC +00:00],
   ["name", "first_page"], ["subject_id", 1],
   ["updated_at", Sun, 26 Jan 2014 16:22:05 UTC +00:00]]
   commit transaction
>> => #<Page id: 1,
             name: "first_page",
             subject_id: 1,
             created_at: "2014-01-26 16:22:05",
             updated_at: "2014-01-26 16:22:05">

> first_page.subject
>> => #<Subject id: 1,
                 name: "math",
                 created_at: "2014-01-26 16:16:26",
                 updated_at: "2014-01-26 16:16:26">

> sub.page
>> => => #<Page id: 1,
                name: "first_page",
                subject_id: 1,
                created_at: "2014-01-26 16:22:05",
                updated_at: "2014-01-26 16:22:05">

参考元 # thanks

lynda.com Tutorial | Ruby on Rails 3 Essential Training—One-to-one associations - YouTube