Rails 5 敏捷开发一书遇到的问题
第11章 创建基于Ajax的购物车
笔者使用的是rails5.2.3版本,书中使用的是5.0版本
跟着书学习,到11章的Ajax异步刷新出了问题,无法自动刷新,手动刷新发现购物车的数量会变化,说明逻辑没问题,浏览器按F12查看了一下控制台,发现一行错误信息:$ is not defined
因为使用了jquery,而这行提示说明jquery没有引入,看了以下rails官网版本说明,发现5.1及以后的版本移除了jquery的引用,默认是没有的,所以需要手动添加。
https://github.com/rails/jquery-rails
具体做法如下:
1.添加gem ‘jquery-rails’ 到 Gemfile 文件中;
2.The jquery and jquery-ujs files will be added to the asset pipeline and available for you to use. If they’re not already in app/assets/javascripts/application.js by default, add these lines:
//= require jquery
//= require jquery_ujs
If you are running Rails 5.1 and up, and if you have included //= require rails-ujs, then jquery_ujs is not needed anymore. You can just add:
//= require jquery
3.Linux控制台输入bundle install
这样就成功地引入了jquery,异步刷新成功。
最后,学ruby基础用什么系统都随便,但是用 rails开发强烈建议不要使用windows
如果你是手动刷新失败,说明你的代码逻辑有问题,以上内容仅限于测试没报错手动刷新能成功添加的情况。