前回で入力したテキストを一覧表示することができた。
今回は、一覧表示したものを編集したり、削除したりできるようにする。
やること
1.編集機能の追加
2.削除機能の追加
1.編集機能の追加
Routerの確認
# rails routes
Prefix Verb URI Pattern Controller#Action
root GET / textins#index
textins GET /textins(.:format) textins#index
POST /textins(.:format) textins#create
new_textin GET /textins/new(.:format) textins#new
edit_textin GET /textins/:id/edit(.:format) textins#edit
textin GET /textins/:id(.:format) textins#show
PATCH /textins/:id(.:format) textins#update
PUT /textins/:id(.:format) textins#update
DELETE /textins/:id(.:format) textins#destroy
対象は、
edit_textin GET /textins/:id/edit(.:format) textins#edit
Controller(edit)の設定
# vim app/controllers/textins_controller.rb def edit end
の部分を
def edit
@textin = Textin.find(params[:id])
end
へ更新
Viewの作成
# touch app/views/textins/edit.html.erb < h1> id: < %= @textin.id %> text edit< /h1> < %= form_for(@textin) do |f| %> < %= f.label :content, 'text' %> < %= f.text_field :content %> < %= f.submit 'submit' %> < % end %> < %= link_to 'TOP', textins_path %>
画面を見てみる
http://サーバのアドレス:3000/textins/1/edit
編集画面が表示された。

次にsubmitをクリックすると修正を実行し、トップページへ戻るようにする。
コントローラの編集
def update end
の部分を
def update
@textin = Textin.find(params[:id])
@textin.update(textin_params)
redirect_to :root
end
へ更新
次に、今のままだと、どこからも編集画面に行けないので、トップ画面から編集画面へ行けるようにトップ画面にリンクをつける。
Viewの編集
# vim app/views/textins/index.html.erb
< h1> TEST TEXT< /h1>
< ul>
< % @textins.each do |textin| %>
< li> < %= textin.content %> < /li>
< %= link_to 'edit', edit_textin_path(textin.id)%>
< % end %>
< /ul>
< %= link_to 'link to text new', new_textin_path %>
太字の< %= link_to 'edit', edit_textin_path(textin.id)%> を追加
画面を確認してみる。
editへのリンクが表示された。

編集画面が表示された。
rails text new を rails text edit に修正し、submitをクリックする。

ちゃんと修正されていました。

次は削除できるようにする
2.削除機能の追加
Routerの確認
# rails routes
Prefix Verb URI Pattern Controller#Action
root GET / textins#index
textins GET /textins(.:format) textins#index
POST /textins(.:format) textins#create
new_textin GET /textins/new(.:format) textins#new
edit_textin GET /textins/:id/edit(.:format) textins#edit
textin GET /textins/:id(.:format) textins#show
PATCH /textins/:id(.:format) textins#update
PUT /textins/:id(.:format) textins#update
DELETE /textins/:id(.:format) textins#destroy
削除の対象ルートは
DELETE /textins/:id(.:format) textins#destroy
コントローラの設定
# vim app/controllers/textins_controller.rb def destroy end
の部分を
def destroy
Textin.find(params[:id]).destroy
redirect_to :root
end
へ変更
VIEWの設定
トップページに各テキストごとの削除ボタンをつける
# vim app/views/textins/index.html.erb
< ul>
< % @textins.each do |textin| %>
< li> < %= textin.content %> < /li>
< %= link_to 'edit', edit_textin_path(textin.id) %>
< %= link_to 'delete', textin, method: :delete, data: { confirm: 'really?'} %>
< % end %>
< /ul>
< %= link_to 'link to text new', new_textin_path %>
太字部分を追加
ブラウザで画面を確認

deleteできるようになった。
見た目はあれですが、これで機能的にはtodoリストのようなあアプリが出来上がった。
次は見た目をなんとかしたいと思う。