Topic

练习笔记

1.Create new projects

ruby -v

rails -v

mkdir Workbook

cd Workbook

rails new suggestotron

cd suggestotron

bundle install

重开rails s

http://localhost:3000

保存

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

http://localhost:3000/topics

打开编辑器

Edit routes.rb

root "topics#index”

http://localhost:3000/

保存

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

......
+ <%= pluralize(topic.votes.count, "vote") %>
+ <%= button_to '+1', upvote_topic_path(topic), method: :post %>
  <%= link_to 'Show', topic %>
......
  <% 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

- Description
......
- <%= topic.title %>
+ <%= link_to topic.title, topic %>
- <%= topic.description %>
- <%= link_to 'show', topic %>
- <%= link_to 'Edit', edit_topic_path(topic) %>
- <%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %>
+ <%= link_to 'Delete', topic, method: :delete, data: { confirm: 'Are you sure?' } %>

http://localhost:3000

4.保存(Save)

git add .

git commit -m "create topics votes"

你可能感兴趣的:(Topic)