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

......
+ <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?' } %>

http://localhost:3000

4.保存(Save)

git add .

git commit -m "create topics votes"

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。