プロジェクト

全般

プロフィール

操作

ScaffoldPlusAnswerThree » 履歴 » リビジョン 12

« 前 | リビジョン 12/17 (差分) | 次 »
Yuumi Yoshida, 2011-08-07 10:52


h1. 演習3解答例

h2. 作業手順

rails generate model user name:string user_id:integer
rails generate migration AddUserIdToTodo user_id:integer
rake db:migrate
rails 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.all # users の確認
Todo.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カラム表示用のコードを追加


Due:
<%25=h @todo.due %25>

Task:
<%25=h @todo.task %25>

##(
Name:
<%25=h @todo.user.name %25>
)##

Memo:
<%25=new_line(h(@todo.memo)) %25>

<%25= link_to 'Edit', edit_todo_path(@todo) %25> |
<%25= link_to 'Back', todos_path %25>

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

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

Editing todo

<%25= error_messages_for :todo %25>

<%25 form_for(@todo) do |f| %25>

Due
<%25= f.date_select :due %25>

Task
<%25= f.text_field :task %25>

##(
Name
<%25= f.select :user_id, User.find(:all).collect {|u| [ u.name, u.id ] } %25>
)##

Memo
<%25= f.text_area :memo %25>

<%25= f.submit "Update" %25>

<%25 end %25>

<%25= link_to 'Show', @todo %25> |
<%25= link_to 'Back', todos_path %25>

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

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

New todo

<%25= error_messages_for :todo %25>

<%25 form_for(@todo) do |f| %25>

Due
<%25= f.date_select :due %25>

Task
<%25= f.text_field :task %25>

##(
Name
<%25= f.select :user_id, User.find(:all).collect {|u| [ u.name, u.id ] } %25>
)##

Memo
<%25= f.text_area :memo %25>

<%25= f.submit "Create" %25>

<%25 end %25>

<%25= link_to 'Back', todos_path %25>

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