Ruby on rails  入门笔记(二)

基于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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值