一、新建rails项目步骤:
1.生成新项目
rails new demo

cd demo
vi Gemfile
末尾end前增加
  gem 'execjs'
  gem 'therubyracer'
 
2.测试服务是否可用
rails s -b 0.0.0.0
 
3.配置root页面(可忽略)
root to: redirect('/ccconsole/chart')
 
4.配置数据库(可忽略)
vi config/database.yml
(1)sqlite3(默认)
development:     
   adapter: sqlite3     
   database: db/development.sqlite3     
   pool: 5     
   timeout: 5000  
   
(2)postgresql
development:
  adapter: postgresql
  host: 9.186.88.100
  database: ccdb
  port: 5432
  username: postgres
  password: xx
  encoding: utf8
 
二、rails生成空数据库
(1)创建数据库(只需执行一次,可忽略)
rake db:create
 
(2)创建执行的migrate 表文件
rails g scaffold book name:string
注意:
1.都是小写。
2.如果你数据库创建了book这张表,他会报错。 
3.scffold生成表,表名会变成复数。
4.会自动生成id、created_at、updated_at字段。
5.常用有的类型 integer string float boolean decimal text
ruby是弱类型语言,对变量的定义不是很严格。
 
(3)制动 在数据库创建表
rake db:migrate RAILS_ENV=development
 
其他:
/config/routes.rb这个文件可配置路由。 
 
3.
生成model、controller、view
rails g scaffold book name price:integer
rake db:migrate RAILS_ENV=development
 
用migrate方式修改数据:
新建20170320141610_update_techspec_mapping.rb
class UpdateTechspecMapping < ActiveRecord::Migration
  def change
    TechspecMapping.where(字段: '修改前的值').update_all(字段: '修改后的值')
  end
end
 
执行:    rake db:migrate VERSION=20120613163818
回退:    rake db:migrate:down VERSION=20120613163730
回退rails g scaffold 命令       rails destroy scaffold 表名
看rails路径命令  rake routes
 
rails命令:
(1)生成model相关文件
rails g scaffold compliancerun starttime:timestamp node server_num:integer
(2)修改model
rails g migration add_column_to_updatedresources cookbook:string
 
rake db:seed 报错
bundle exec rake db:migrate
bundle update
 
三、配置404,500等页面
vi config/routes.rb
  get '500', :to => 'custom_errors#server_error'
  get '502', :to => 'custom_errors#server_error'
  get '504', :to => 'custom_errors#server_error'
  get '422', :to => 'custom_errors#server_error'
  get '404', :to => 'custom_errors#rescue404'

四、rails项目目录结构(程序自动生成)

1.app文件夹(rails的核心部分,也可以说存放的是针对项目的所有代码)
包括6个子文件夹 
  assets       图片、js和样式表 
  controllers  驱动业务逻辑的控制器
  helpers      视图辅助类,一些常用的代码段
  mailers      与邮件服务相关的类
  models       数据描述结构、验证和完整性规则等模块
  views        生成html的所有模块文件,也可以存放css、图片
 
2.public 存储rails应用的公共资源,如出错时的默认页和首页等。
3.script 各种脚本,如代码生成器脚本。
4.test 单元测试和功能测试
5.vendor 程序依赖的外部类库,和lib一样都可以被自动加载。
6.config 服务器、数据库或其他文件相依赖的配置文件
  database.yml 数据库配置
  ----adapter数据库连接库(适配器),默认sqlite3
  ----database数据库名称
  ----pool连接池数量
  ----timeout经过多少毫秒后服务器自动放弃连接,默认为5000ms。
7.db 数据库脚本
8.doc 文档
9.lib 类库
10.log 操作日志
11.其他文件
.gitignore 记录哪些是需要忽略,不需要追踪的文件
config.ru 基于rack服务器的配置来启动应用程序
Gemfile 允许我们指定哪些gem是rails应用程序所依赖的
Rakefile 包含了一些可以在命令行下运行的作业
README 包含了应用程序的简要说明

五、增加自定义页面方法

(1)config/routes.rb
get "detailreports" => "complianceruns#report"
(2)controller中
def report
  xx 
  render :report 
end
(3)  
views/complianceruns/中新建report.html.erb

六、rails task

rake命令
在项目lib/task中新建test.rb

namespace :test do
  task :hello do
    puts 'hello'
  end
end
 
运行:
rake test:hello

七、rails发邮件

1) update the /etc/postfix/main.cf by adding the following settings in the end:
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:用户:密码
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_tls_CAfile = /etc/postfix/ssl/gd_bundle-g2-g1.crt
header_size_limit = 4096000
relayhost = [smtp.sendgrid.net]:587
 
   assuming to use sendgrid, and I had a trial account as specified in smtp_sasl_password_maps
 
2) download the CA file specifed in 1)
      cd /etc/postfix/ssl
 
3) restart the postfix
      /etc/init.d/postfix restart
 
4) it may need to install a missing moduel
     yum install cyrus-sasl-plain
 
1.Gemfile中增加 
gem 'rake', '11.3.0'
 
2.项目根目录运行
rails g mailer UserMailer
 
3.vi app/mailers/user_mailer
增加
  default from: "xx@163.com"
  def send_mail(params = {})
    @url  = 'http://example.com/login'
    mail( :subject => 'abc',
          :to => "xx@qq.com",
          :from => 'xx@163.com',
          :date => Time.now
        )   
  end
 
4.vi config/environments/development.rb
增加
ActionMailer::Base.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default :charset => "utf-8"
  config.action_mailer.default_url_options = { :host => 'localhost:3000' }  
  ActionMailer::Base.smtp_settings = { 
:address => "smtp.163.com", 
:port => 25, 
:domain => "163.com", 
:authentication => :login, 
:user_name => "xx@163.com", 
:password => "xx"
  }

八、项目中增加bootstrap

(1)、在Gemfile中增加 gem 'bootstrap-sass', '~> 3.2.0.2'
(2)、bundle install
(3)、把assets/stylesheets/application.css重命名为application.css.scss
(4)、在这个文件中增加:
@import "bootstrap-sprockets";
@import "bootstrap";
(5)、在assets/javascriptsheets/application.js中增加://= require bootstrap-sprockets
 
九、分页
will_paginate
 .paginate(:per_page => pageSize, :page => pageNumber)
 
十、导出csv
def export_to_csv
    logger.debug "whyrun report export start: #{DateTime.now}"
    startDateUnixTime = params[:startDateUnixTime]
    endDateUnixTime = params[:endDateUnixTime]
    searchString = params[:searchString]
    searchColumns = params[:searchColumns]
 
    if validate_date_in_millisecs(startDateUnixTime) || validate_date_in_millisecs(endDateUnixTime) || validate_string(searchString,'searchString') || validate_string(searchColumns,'searchColumns')
      return
    end
 
    options = {
        :startDateUnixTime => startDateUnixTime,
        :endDateUnixTime => endDateUnixTime,
        :searchString => searchString,
        :searchColumns => searchColumns,
    }
    whyrun_reports = WhyrunReport.search(options)
    logger.debug "write file start: #{DateTime.now}"
 
    time = Time.now.strftime('%Y%m%d%H%M%S')
    zipstream = Zip::OutputStream.write_buffer do |zos|
      zos.put_next_entry "Compliance_Check_Report_#{time}.csv"
      zos.print "Server, Platform, Start Time, Tech spec, Policy, Validation, Policy Attribute, Required Value, Current Value, Compliant, Action to Remediate, Environment, Profile, Description \n"
      for i in 0..whyrun_reports.length-1
        server = whyrun_reports[i]['server'] || ''
        platform = whyrun_reports[i]['platform'] || ''
        startTime = whyrun_reports[i].starttime.strftime('%Y-%m-%dT%H:%M:%S.%3NZ') || ''
        techspec = whyrun_reports[i]['techspec'] || ''
        environment = whyrun_reports[i]['environment'] || ''
        profile = whyrun_reports[i]['profile'] || ''
        description = whyrun_reports[i]['description'] || ''
 
        data = [server, platform, startTime, techspec, policy, validation, policy_attribute, requiredValue, currentValue, compliant, action_to_remediate, environment, profile, description]
        zos.print data.to_csv
      end
    end
    zipstream.rewind
 
    send_data zipstream.string, filename: "Compliance_Check_Report_#{time}.zip", disposition: 'attachment'
    logger.debug "export end: #{DateTime.now}"
  end
 
 
Ruby on Rails 指南 (v5.1.1)

ruby on rails笔记的更多相关文章

  1. [Ting's笔记Day4]将Ruby on Rails项目部署到Heroku

    今天想笔记的是把自己写的Ruby on Rails项目部署(Deploy)到Heroku! Heroku是Salesforce公司旗下的云端服务商,支持多种程序语言像是Ruby,PHP,Python等 ...

  2. [Ting's笔记Day1] Ruby on Rails练习- MacOS安装篇

    千里之行,始于足下.喊了要学Ruby on Rails好久,今天终于要来迈向第一步:安装了! 一开始学习新的事物,主要就是跟着这个网页所说的步骤step by step. 很喜欢这个网页的设计流程,透 ...

  3. Ruby on Rails Tutorial读书笔记-1

    只是怕忘了命令,全部撸一次,记个大概.. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 安装Ruby之前,先要安装RVM: curl -L https://get.rvm.io | bas ...

  4. Ruby on Rails 开发笔记

    安装 Ruby on Rails Install Rails: A step-by-step guide 创建应用 # 创建新的应用程序 $ rails new blog $ cd blog # 启动 ...

  5. Ruby on Rails Tutorial 第2版 学习笔记

    Ruby on Rails Tutorial 第2版 在线阅读:http://railstutorial-china.org/ 英文版:http://ruby.railstutorial.org/ru ...

  6. 《Ruby on Rails教程》学习笔记

    本文是我在阅读 Ruby on Rails 教程的简体中文版时所做的摘录,以及学习时寻找的补充知识.补充知识主要来自于 Ruby on Rails 實戰聖經. Asset Pipeline 在最新版 ...

  7. Linux超快速安装Ruby on Rails

    Linux超快速安装Ruby on Rails 时间 2014-11-25 11:45:11 Flincllck Talk 原文  http://www.flincllck.com/quick-ins ...

  8. 管理不同版本ruby和rails的利器——rvm

    近年来,ruby on rails逐渐火了起来,我想各位码农早就耳闻,特别是那些做B/S项目的童鞋,早就想跃跃一试了. 笔者也是初次接触ruby on rails ,我想,对于初学者来说,最好的学习方 ...

  9. ruby on rails on windows

    这次想系统学会rails,最终目标是将redmine改造成顺手的工具,主要的手段就是开发redmine插件.虽然网上都推荐使用类Unix系统,可手头只有win7系统,就安装了. 难免会遇到这样那样的问 ...

随机推荐

  1. Django之Form操作

    一.Form基础 (一)Form的作用 Django的Form主要有以下几大作用: 生成HTML标签 验证用户数据(显示错误信息) Form提交保留上次提交数据 初始化页面显示数据 (二)实例 一般网 ...

  2. express 使用art-template模板引擎

    下载express-art-template art-template - app.js中配置 - 注册一个模板引擎 - `app.engine('.html',express-art-templat ...

  3. TCP的状态及变迁

    十一种状态如下图: 全部11种状态1. 客户端独有的:(1)SYN_SENT (2)FIN_WAIT1 (3)FIN_WAIT2 (4)CLOSING (5)TIME_WAIT .2. 服务器独有的: ...

  4. Qt 【关于控件样式,鼠标进入、离开、点击】

    比如举以下这个例子: QPushButton * okBtn; okBtn->setstylesheet("QPushButton{border-image:url(:/image/h ...

  5. 小程序入坑(一)---如何引入iconfont 字体图标

    最近一直忙于日常任务,其实是懒癌又犯了..........不过因为自己的“懒癌”,“不思进取”给自己挖了不少坑. 一,小程序工具的安装 打开简易小程序的官网https://mp.weixin.qq.c ...

  6. Java 基础 - System.arraycopy() 浅拷贝 深拷贝

    ref: https://blog.csdn.net/balsamspear/article/details/85069207 https://blog.csdn.net/balsamspear/ar ...

  7. Java——异常的基本概念

    1.异常的基本概念 1.1什么是异常 在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格 ...

  8. Nginx缓存配置指南

    1.如何配置基本缓存设置 开启简单的缓存配置,只需要两个指令:proxy_cache_path和proxy_cache.proxy_cache_path配置缓存的存放地址和其他的一些常用配置,prox ...

  9. 分块——cf1207F

    这么傻逼的题当时想了那么久 用a数组维护原序列,b[i][j]表示 pos%i=j 的 a[pos]之和 对于每个修改1 x y,先直接修改a[x],然后枚举i=1..700,修改b[i][x%i] ...

  10. BZOJ 2055: 80人环游世界(有上下界的费用流)

    题面 Time Limit: 10 Sec Memory Limit: 64 MB Submit: 693 Solved: 434 [Submit][Status][Discuss] Descript ...