プロジェクト

全般

プロフィール

操作

ScaffoldPlusAnswerThree » 履歴 » リビジョン 8

« 前 | リビジョン 8/17 (差分) | 次 »
Yuumi Yoshida, 2008-07-13 17:40


h1. 演習3解答例

h2. 作業手順

ruby script/generate model user name:string user_id:integer
ruby script/generate migration AddUserIdToTodo user_id:integer
rake db:migrate
ruby script/console # usersデータの作成,todos.user_id更新
User.new(:id=>1, :name=>'山田')
u.save
u = User.new(:id=>2, :name=>'川田')
u.save
Todo.update_all("user_id=1")
User.find(:all) # users の確認
Todo.find(:all) # todos の確認
quit

h2. 変更点

h3. 1. app/models/user.rb

Todoとの一対多の関連を記述

class User < ActiveRecord::Base
##(has_many :todos)##
end

h3. 2. app/models/todo.rb

Userとの多対一の関連(従属)を記述

class Todo < ActiveRecord::Base
##(belongs_to :user)##
end

h3. 3. app/views/todos/index.html.erb

user.nameカラム表示用のコードを追加

Listing todos

Due
##(Name)##
Task

<%25 for todo in @todos %25>

<%25=h todo.due %25>
##(<%25=h todo.user.name %25>)##
<%25=h todo.task %25>
<%25= link_to 'Show', todo %25>
<%25= link_to 'Edit', edit_todo_path(todo) %25>
<%25= link_to 'Destroy', todo, :confirm => 'Are you sure?', :method => :delete %25>

<%25 end %25>

<%25= link_to 'New todo', new_todo_path %25>

h3. 4. app/views/todos/show.html.erb

user.nameカラム表示用のコードを追加

h3. 5. app/views/todos/edit.html.erb

user.name入力表示用のコードを追加

h3. 6. app/views/todos/new.html.erb

user.name入力表示用のコードを追加

h2. ソースコード

解答例のソースコードは http://www.ey-office.com/trac/rails/browser/tags/todo_q3で参照できます。

Yuumi Yoshida さんがほぼ16年前に更新 · 8件の履歴