Rails5でデータの編集機能を実装する
前提
MacOS 10.14.5
Ruby 2.5.0
Rails 5.2.3
- 編集機能はPaymentモデルに実装する
- Deviseをインストール済み
手順
1. paymentsコントローラに追記
def edit @payment = current_user.payments.find(params[:id]) end def update @payment = current_user.payments.find(params[:id]) if current_user.update(payment_params) redirect_to payments_path, notice: "支払い「#{@payment.item}」を更新しました。" else render :edit end end
2. 編集のためのViewを作成
- app/views/paymentにedit.html.erbを作成する
内容は以下
<%= form_with model: @payment, local: true do |form| %> <%= form.label :item, 'アイテム' %> <%= form.text_field :item %> <%= form.label :price, '支払い' %> <%= form.text_field :price %> <%= form.label :category, '分類' %> <%= form.text_field :category %> <%= form.submit %> <% end %>
3. routesを編集
resources :payments, only: [:index, :new, :create, :edit, :update]
4. 一覧ページに編集ボタンを追加
<table> <tr> <th><%= Payment.human_attribute_name(:created_at) %></th> <th><%= Payment.human_attribute_name(:item) %></th> <th><%= Payment.human_attribute_name(:price) %></th> <th><%= Payment.human_attribute_name(:category) %></th> </tr> <% @payments.each do |payment| %> <tr> <td><%= payment.created_at.strftime('%Y/%m/%d') %></td> <td><%= payment.item %></td> <td><%= payment.price %></td> <td><%= payment.category %></td> <td><%= link_to '編集', edit_payment_path(payment) %></td> </tr> <% end %> </table>
以上