控制台创建一个博客项目
rails new blog
cd blog
rails g scaffold post title:string text:text
rails g model comment post_id:integer text:text
rake db:migrate
rails s
测试:http://localhost:3000/posts
修改index.html.erb
blog/app/views/posts/index.html.erb
删除原有的内容,新的内容如下:
h1%=?@post.title?%/h1??
??
%=?@post.text?%??
??
p??
%=?link_to?Back,?posts_path?%??
|??
%=?link_to?Edit,?edit_post_path(@post)?%??
|??
%=?link_to?Delete,@post,:method?=?:delete,?:confirm?=?Are?you?sure??%??
/p ?
来源:?/pan_tian/article/details/8763627
增加Comments项
继续修改show.html.erb
blog/app/views/posts/show.html.erb
h1%=?@post.title?%/h1??
??
%=?@post.text?%??
??
h2Comments/h2??
??
%?@ments.each?do?|comment|?%??
??p%=?comment.text?%/p??
??p%=?time_ago_in_words?comment.created_at?%?ago?/p??
%?end?%??
??
%=?form_for?[@post,@ments.build]?do?|f|?%??
??p%=?f.text_area?:text,?:size?=?40x10?%?/p??
??p%=?f.submit?Post?Comment?%?/p??
%?end?%??
??
p??
%=?link_to?Back,?posts_path?%??
|??
%=?link_to?Edit,?edit_post_path(@post)?%??
|??
%=?link_to?Delete,@post,:method?=?:delete,?:confirm?=?Are?you?sure??%??
/p ?
修改blog/app/models/post.rb
增加 ?has_many?:comments??
修改blog/app/models/comment.rb
增加?belongs_to?:post?
修改blog/config/routes.rb
resources?:posts?do??
????resources?:comments??
??end??
这个时候Comment就出来了,但是如果提交comment,还会报错,因为我们还没写comment的controller
打开一个新的命令行
D:\Ruby\projectscd blogD:\Ruby\projects\blograils g controller comments create destroy
打开新创建的blog\app\controllers\comments_controller.rb
class?CommentsController??ApplicationController??
??def?create??
????@post?=?Post.find(params[:post_id])??
? ?@comment?=?@ments.build(comment_params)???
????@comment.save??
??
????redirect_to?@post??
??end??
??def?comment_params
params.require(:comment).permit(:id, :text)
end
??def?destroy??
??end??
end??
增加删除comment功能
修改blog/app/views/posts/show.html.erb
(增加Delete Comment链接)
h1%=?@post.title?%/h1??
??
%=?@post.text?%??
??
h2Comments/h2??
??
%?@ments.each?do?|comment|?%??
??p%=?comment.text?%/p??
??p
您可能关注的文档
最近下载
- 文学类文本陈国凡《饭局》阅读练习及答案(湖南2022届高三下5月).docx VIP
- 地基基础 课程教案.doc VIP
- 电力专业英语词汇.doc VIP
- 色度-方法确认报告方法验证方法证实报告.docx VIP
- 《Python程序设计实验》课程大纲(本科).docx VIP
- 七年级上册第二单元+友谊的天空+课件-2026年 中考道德与法治一轮复习.pptx VIP
- 河流动力学概论绪论.pptx VIP
- 一种基于数字孪生的仿真推演系统.pdf VIP
- 7.2.2“白山黑水”——东北三省 课件 2025-2026学年人教版地理八年级下册.pptx VIP
- 2025年陕西省中考语文试卷真题及答案详解(精校打印版).docx
原创力文档

文档评论(0)