练习笔记
1.Create new projects
ruby -v
rails -v
mkdir Workbook
cd Workbook
rails new suggestotron
cd suggestotron
bundle install
重开rails s
保存
git init
git status
git add .
git commit -m "Added all the things"
2.建立topic scaffold
git checkout -b topic_scaffold
rails generate scaffold topic title:string description:text
rake db:migrate
重开rails s
打开编辑器
Edit routes.rb
root "topics#index”
保存
git add .
git commit -m "add README"
3.添加点赞功能
git checkout -b vote
Create model
rails generate model vote topic_id:integer
rake db:migrate
Edit app/models/topic.rb
has_many :votes, dependent: :destroy
Edit app/model/vote.rb
belongs_to :topic
rails c
Topic.count
my_topic = Topic.first
my_topic.update_attributes(title: 'Edited in the console')
my_topic.votes.create
my_topic.votes.count
my_topic.votes.first.destroy
exit
Edit app/controllers/topics_controller.rb_
def upvote
@topic = Topic.find(params[:id])
@topic.votes.create
redirect_to(topics_path)
end
Edit config/routes.rb
resources :topics do
member do
post 'upvote'
end
end
Edit app/views/topics/index.html.erb
......
+ <td><%= pluralize(topic.votes.count, "vote") %></td>
+ <td><%= button_to '+1', upvote_topic_path(topic), method: :post %></td>
<td><%= link_to 'Show', topic %></td>
......
<% end %>
Edit app/controllers/topics_controller.rb
def create
......
- format.html { redirect_to @topic, notice: 'Topic was successfully cteated.' }
+ format.html { redirect_to topics_path, notice: 'Topic was successfully created.' }
......
def update
......
- format.html { redirect_to @topic, notice: 'Topic was successfully updated.' }
+ format.html { redirect_to topics_path, notice: 'Topic was successfully update.' }
Edit app/views/topics/index.html.erb
- <th>Description</th>
......
- <td><%= topic.title %></td>
+ <td><%= link_to topic.title, topic %></td>
- <td><%= topic.description %></td>
- <td><%= link_to 'show', topic %></td>
- <td><%= link_to 'Edit', edit_topic_path(topic) %></td>
- <td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %>
+ <td><%= link_to 'Delete', topic, method: :delete, data: { confirm: 'Are you sure?' } %>
4.保存(Save)
git add .
git commit -m "create topics votes"