锦囊妙计-前端篇
锦囊妙计-前端篇
Lose your first 50 games as quickly as possible. - 围棋谚语
Build your first 50 Rails apps as quickly as possible. - 造样造句
Bootstrap
Bootstrap是目前最流行的前端设计框架,让开发者也可以很轻松的进行网页排版,也很有多现成的 Theme 可以套用。要在 Rails 使用 Bootstrap ,请安装 bootstrap-sass
如果搭配分页套件 kaminari 的话,执行 rails generate kaminari:views bootstrap3 就会产生对应的 kaminari 样板。
进一步可以参考Integrating Rails and Bootstrap这一系列文章。
Font Awesome
即将推出的 Bootstrap 4 将会移除 Glyphicons,所以目前大家推荐使用 Font-Awesome
Rails 可以安装 <https://github.com/bokmann/font-awesome-rails> 这个 gem
表单
除了用 Rails 内建的表单 Helper ,也有一些提供表单设计更方便的套件:
select2 厉害的下拉选单
<https://github.com/argerim/select2-rails>
- 支援 Autocomplete 的 select 单选
- 支援 Autocomplete 的 select 多选
- 支援 Tagging UI (text_field)
- 可用 Ajax 捞资料Example code: <https://github.com/ihower/rails-exercise-ac5/blob/master/app/views/events/_form.html.erb>
漂亮的 Date/Time 输入和输出
表单输入
- 只有日期 <https://github.com/Nerian/bootstrap-datepicker-rails>
- Example code: <https://github.com/ihower/rails-exercise-ac5/blob/master/app/views/events/_form.html.erb>
- 日期+时间
- <https://github.com/TrevorS/bootstrap3-datetimepicker-rails>
- <http://eonasdan.github.io/bootstrap-datetimepicker/>
调整显示格式
- Ruby 内建的方法: Datetime#strftime
- Rails 内建的方法: datetime.to_s(:short) <http://railscasts.com/episodes/31-formatting-time?view=asciicast>
- 增加或变更 Rails 的时间日期 to_s,修改
config/application.rb在最下面插入:
Date::DATE_FORMATS[:short] = "%Y/%m/%d"
Time::DATE_FORMATS[:short] = "%Y/%m/%d %H:%M"
Admin 接口
管理员后台除了自己盖,有一些 gem 可以很快速的盖起来,例如这两套:
缺点:想要扩充或修改的时候,会碰到限制和麻烦。
如何画图表
常用图表包括 Line chart、Pie chart、Column chart、Bar chart 等等,最常见使用 Google Charts 或 Highcharts 和 D3.js
搭配 Rails 的话,可以安装 <https://github.com/ankane/chartkick> 这一套最简单,但功能较少。或是笔者推荐使用 Chart.js。
自订 URL 网址
可以让使用者自订,或是乱数产生当作 URL<http://railscasts.com/episodes/63-model-name-in-url-revised>
范例:
- AC4 <https://github.com/ihower/rails-exercise-ac4/commit/a27c59dd2d8e311cf0d87d30f70630fb6bf153d7>
- AC5
- <https://github.com/ihower/rails-exercise-ac5/commit/f98d20f0e37d13796b4005f971ae77bd3ab27ef5>
- <https://github.com/ihower/rails-exercise-ac5/commit/b7302cf361ddc1f345cee3595ba50c283775fca1>
Nested Form (1-to-many)
1 对 1 的表单
使用 Rails 内建的 fields_for 就可以完成,参考 <https://ihower.tw/rails4/restful-practices.html>
1 对多的表单
如果知道固定N笔,作法同上。但如果需要可以动态加减数量,则需要 JavaScript 协助动态增减字段。
可以使用 <https://github.com/ncri/nested_form_fields> gem (注意 Strong Parameter,这个 gem 的 README 没提到) 或 <https://github.com/nathanvda/cocoon>另外参考 <http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html> 的 reject_if 用法
范例 Example Code: <https://github.com/ihower/rails-exercise-ac3/tree/nested_form>
Recapache
- Recaptcha 是做 captcha 最简单快速的方式。
