現在來做點擊 Like 的數字選項數字加1後會更新的玏能
app/controllers/girbs_controller.rb
class GirbsController < ApplicationController
def index
@girbs = Girb.all
end
def like
@girb = Girb.find(params[:id])
@girb.like += 1;
@girb.save
redirect_to(girbs_path)
end
end
在 routes 增加新增加的 like
config/routes.rb
Rails.application.routes.draw do
resources :girbs do
member do
post :like
end
end
end
修改相對應的 view
app/views/girbs/index.html.erb
<h1>Index Page of Girb</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Like</th>
</tr>
</thead>
<tbody>
<% @girbs.each do |girb| %>
<tr>
<td><%= girb.name %></td>
<td><%= girb.email %></td>
<td>
<%= link_to like_girb_path(girb.id), method: :post do %>
<%= girb.like %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
鍵入
http://localhost:3000/girbs
然後點擊 Like 的數字就可以看到數字可以加1了