プロジェクト

全般

プロフィール

操作

ScaffoldPlusAnswerThree » 履歴 » リビジョン 6

« 前 | リビジョン 6/17 (差分) | 次 »
Yuumi Yoshida, 2008-01-13 18:00


= 演習3解答例 =

== 作業手順 ==
{{{
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
}}}

== 変更点 ==

=== 1. app/models/user.rb ===
Todoとの一対多の関連を記述
{{{
#!html
class User < ActiveRecord::Base
has_many :todos
end

}}}

=== 2. app/models/todo.rb ===
Userとの多対一の関連(従属)を記述
{{{
#!html
class Todo < ActiveRecord::Base
belongs_to :user
end

}}}

=== 3. app/views/todos/index.html.erb ===
user.nameカラム表示用のコードを追加
{{{
#!html
<h1>Listing todos</h1>

<table>
<tr>
<th>Due</th>
<th>Name</th>
<th>Task</th>
</tr>

<%25 for todo in @todos %25>
<tr>
<td><%25=h todo.due %25></td>
<td><%25=h todo.user.name %25></td>
<td><%25=h todo.task %25></td>
<td><%25= link_to 'Show', todo %25></td>
<td><%25= link_to 'Edit', edit_todo_path(todo) %25></td>
<td><%25= link_to 'Destroy', todo, :confirm => 'Are you sure?', :method => :delete %25></td>
</tr>
<%25 end %25>
</table>

<br />

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

}}}

=== 4. app/views/todos/show.html.erb ===
user.nameカラム表示用のコードを追加
{{{
#!html
<p>
<b>Due:</b>
<%25=h @todo.due %25>
</p>

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

<p>
<b>Name:</b>
<%25=h @todo.user.name %25>
</p>

<p>
<b>Memo:</b><br/>
<%25=new_line(h(@todo.memo)) %25>
</p>

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

}}}

=== 5. app/views/todos/edit.html.erb ===
user.name入力表示用のコードを追加
{{{
#!html
<h1>Editing todo</h1>

<%25= error_messages_for :todo %25>

<%25 form_for(@todo) do |f| %25>
<p>
<b>Due</b><br />
<%25= f.date_select :due %25>
</p>

<p>
<b>Task</b><br />
<%25= f.text_field :task %25>
</p>

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

<p>
<b>Memo</b><br />
<%25= f.text_area :memo %25>
</p>

<p>
<%25= f.submit "Update" %25>
</p>
<%25 end %25>

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

}}}

=== 6. app/views/todos/new.html.erb ===
user.name入力表示用のコードを追加
{{{
#!html
<h1>New todo</h1>

<%25= error_messages_for :todo %25>

<%25 form_for(@todo) do |f| %25>
<p>
<b>Due</b><br />
<%25= f.date_select :due %25>
</p>

<p>
<b>Task</b><br />
<%25= f.text_field :task %25>
</p>

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

<p>
<b>Memo</b><br />
<%25= f.text_area :memo %25>
</p>

<p>
<%25= f.submit "Create" %25>
</p>
<%25 end %25>

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

}}}

== ソースコード ==

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

Yuumi Yoshida さんが16年以上前に更新 · 6件の履歴