第二課加分題解法

1. 增加 -1的按鈕

app/controllers/topics_controller.rb裡增加

app/controllers/topics_controller.rb
  def downvote
    @topic = Topic.find(params[:id])
    @topic.votes.first.destroy
     redirect_to(topics_path)
  end

config/routes.rb裡加入 post 'downvote'

config/routes.rb
   member do
     post 'upvote'
     post 'downvote'
   end
app/views/topics/index.html.erb
<td><%= button_to '+1', upvote_topic_path(topic), method: :post %></td>
<td><%= button_to '-1', downvote_topic_path(topic), method: :post %></td>

2. 根据投票分数排序 topics

這裡照抄同學的代碼(因為根本沒教過)

app/views/topics/index.html.erb
-  <% @topics.each do |topic| %>
+ <% @topics.sort_by {|topic| -topic.votes.count}.each do |topic| %>

3.新增一个 'about' 页面

touch app/views/topics/about.html.erb

app/views/topics/about.html.erb
<h2>About</h2>
nothing about this page<br><br>
<%= link_to 'Back', topics_path %>
app/views/topics/index.html.erb
<%= link_to 'New Topic', new_topic_path %>
+ <%= link_to 'About', about_path %>

最后在 config/routes.rb 里输入
get 'about' => 'topics#about'

這個步驟不太懂為什麼要加在routes裡
應該要再研究一下ruby的框架

comments powered by Disqus