Open /app/views/ideas/index.html.erb
Replace
<td><%= link_to 'Show', idea %></td>
With
<td><%= link_to 'Show', idea, class: 'test' %></td>
Open /app/assets/stylesheets/application.css
Add
a.test { font-weight: bold; color: red; text-decoration:none;}
a.test:visited { font-weight: bold; color: red;}
td { padding: 10px;}
Open /app/controllers/ideas_controller.rb
After
@ideas = Idea.all
Add
chars_to_display = 50
@ideas.each do |x|
if x.description.length > chars_to_display
x.description = x.description[0, 50] + '...'
end
end
Open your terminal and run the command rails g migration AddFields
Go to db/migrate
Find a file with a similar name: 20130418195753_add_fields.rb
Open it and replace
def up
end
def down
end
end
With
def up
add_column :ideas, :votes, :integer, :default => 0
add_column :ideas, :score, :decimal, :default => 0
end
def down
remove_column :ideas, :votes
remove_column :ideas, :score
end
end
Run the command rake db:migrate
Open app/controllers/ideas_controller.rb
Before the very last
end
Add
def vote
idea = Idea.find(params[:id])
idea.votes += 1
idea.score = idea.score + params[:idea][:score].to_d
idea.save!
redirect_to '/'
end
Open /config/routes.rb
Replace
resources :ideas
With
resources :ideas do
member do
post 'vote'
end
end
Open /app/views/ideas/index.html.erb
After
<td><%= link_to 'Destroy', idea, method: :delete, data: { confirm: 'Are you sure?' } %></td>
Add
<td><span id="score"><%= idea.score.to_d / idea.votes %></span></td>
<td>
<%= form_for(idea, url: vote_idea_path(idea), method: 'post') do |f| %>
1 <input type='radio' name='idea[score]' value='1' />
2 <input type='radio' name='idea[score]' value='2' />
3 <input type='radio' name='idea[score]' value='3' />
4 <input type='radio' name='idea[score]' value='4' />
5 <input type='radio' name='idea[score]' value='5' />
<button>Vote!</button>
<% end %>
</td>
After
<th></th>
Add
<th>Score</th>
<th width="20%">Vote</th>