操作
演習3解答例¶
作業手順¶
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更新
u = 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
変更点¶
1. app/models/user.rb¶
Todoとの一対多の関連を記述
class User < ActiveRecord::Base ##(has_many :todos)## end
2. app/models/todo.rb¶
Userとの多対一の関連(従属)を記述
class Todo < ActiveRecord::Base ##(belongs_to :user)## end
3. app/views/todos/index.html.erb¶
user.nameカラム表示用のコードを追加
<h1>Listing todos</h1>
<table>
<tr>
<th>Due</th>
##(<th>Name</th>)##
<th>Task</th>
</tr>
<% for todo in @todos %>
<tr>
<td><%= todo.due %></td>
##(<td><%= todo.user.name %></td>)##
<td><%= todo.task %></td>
<td><%= link_to 'Show', todo %></td>
<td><%= link_to 'Edit', edit_todo_path(todo) %></td>
<td><%= link_to 'Destroy', todo, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New todo', new_todo_path %>
4. app/views/todos/show.html.erb¶
user.nameカラム表示用のコードを追加
<p> <b>Due:</b> <%= @todo.due %> </p> <p> <b>Task:</b> <%= @todo.task %> </p> ##(<p> <b>Name:</b> <%= @todo.user.name %> </p>)## <p> <b>Memo:</b><br/> <%= new_line(@todo.memo) %> </p> <%= link_to 'Edit', edit_todo_path(@todo) %> | <%= link_to 'Back', todos_path %>
5. app/views/todos/_form.html.erb¶
user.name入力用のコードを追加
<%= form_for(@todo) do |f| %>
<% if @todo.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@todo.errors.count, "error") %> prohibited this todo from being saved:</h2>
<ul>
<% @todo.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :due %><br />
<%= f.date_select :due %>
</div>
##(<div class="field">
<%= f.label :user_id %><br />
<%= f.select :user_id, User.all.collect {|u| [ u.name, u.id ] } %>
</div>)##
<div class="field">
<%= f.label :task %><br />
<%= f.text_field :task %>
</div>
<div class="field">
<%= f.label :memo %><br />
<%= f.text_area :memo %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Yuumi Yoshida さんが約10年前に更新 · 17件の履歴