プロジェクト

全般

プロフィール

操作

ScaffoldPlusAnswerThree » 履歴 » リビジョン 16

« 前 | リビジョン 16/17 (差分) | 次 »
Yuumi Yoshida, 2011-08-13 00:33


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更新
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

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= todo.due %25>
##(<%25= todo.user.name %25>)##
<%25= 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= @todo.due %25>

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

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

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

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

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

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

<%25= form_for(@todo) do |f| %25>
<%25 if @todo.errors.any? %25>

<%25= pluralize(@todo.errors.count, "error") %25> prohibited this todo from being saved:

  <ul>
  <%25 @todo.errors.full_messages.each do |msg| %25>
    <li><%25= msg %25></li>
  <%25 end %25>
  </ul>
</div>

<%25 end %25>

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

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

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


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


<%25= f.submit %25>

<%25 end %25>

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