rubyonrails创建一个博客项目解析.doc

控制台创建一个博客项目 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 blog D:\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

文档评论(0)

1亿VIP精品文档

相关文档