基于scaffold的简单练习
1. 首先建立一个项目demo
在终端执行rails new demo -d mysql 登录数据库后执行rails db:create
2. 我们希望建立一个topic来使大家进行投票,此时的topic可以看做上一节的blog,但是通过scaffold,就不需要一个一个进行CURD的设定。
在终端执行rails g scaffold topic title:string description:text
此时自动生成了MVC相应的文件
3. 此时执行rake db:migrate 将model的数据存入表中
4. rails s 启动服务器
访问 http://localhost:3000/topics
添加路由 root “topics#index”,这样访问根目录也是这个页面了
5. 对topic进行投票
因为投票要计算票数,我们需要表来存储数据,此时就需要建一个模型
rails g model vote topics_id :integer
然后migrate
rake db:migrate
6. 将votes和topics联系起来
在topic的model文件的类里添加一句:
has_many:votes ,dependent: :destroy
然后再在vote的model里加一句 :belongs_to:topic
7. 在终端进行控制
rails c 进入终端
Topic.count可以查看数量
item = Topic.first将第一篇赋给变量item
item.update_attributes(title: ‘Edited in the console’)可以修改名称
item.votes.create 对其投票
8. 加按钮让大家投票
此时需要在控制器里加入新动作upvote
def upvote
@topic=Topics.find(params[:id])
@topic.votes.create
redirect_to (topics_path)
end
9. 更新路由
Rails.application.routes.draw do
root 'topics#index'
resources :topics do
member do
post 'upvote'
end
end
end
10. 在index.html文件里加入
<td><%= pluralize(topic.votes.count, "vote") %></td>
<td><%= button_to '+1', upvote_topic_path(topic), method: :post %></td>
11. 新增后跳回原页面
在控制器的create动作里进行修改,把redirect_to
后面的路径改成topics_path
12. 添加超链接
<td><%= link_to topic.title,topic %></td>
之后我删掉了正文内容,整理样式为
13. 把destroy改成delete
<td><%= link_to 'Delete', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td>