rails5 后台入门(api mode)

时间:2022-07-02 03:42:02

1. Installation (Centos为例)

1.1安装rvm (http://rvm.io/)

gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

\curl -sSL https://get.rvm.io | bash -s stable

1.2安装ruby

rvm install 2.5.3

yum install ruby-dev

1.3 安装rails

gem install rails

2. Setup

2.1 初始化项目

rails new ProjectName --api  ( --skip-bundle ) 跳过bundle安装

gemfile配置

gem 'mysql2' # 如果是pg安装'pg'
gem 'rack-cors'

安装: bundle install

2.2 配置数据库

/config/database.yml

default: &default
adapter: mysql2
pool:
username: root
password: pwdpwdpwd
host: localhost
charset: utf8
timeout: development:
<<: *default
database: databaseName test:
<<: *default
database: databaseName2 production:
<<: *default
database: databaseName3

2.3 配置cors

/config/application.rb

config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'http://localhost:3000'
resource '*', :headers => :any, :methods => [:get, :post, :options,:put,:delete], :credentials=> true
end
end

2.4 配置session和cookie

!  api模式默认不带

/config/application.rb

config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore

/app/controllers/application_controller.rb


  before_action :set_csrf_cookie
include ActionController::Cookies
include ActionController::RequestForgeryProtection # 放最后
private
def set_csrf_cookie
cookies["CSRF-TOKEN"] = form_authenticity_token
end

3. 简单的用户认证和登录

3.1 创建模型

rails g model User username:string email:string password_digest:string

3.2 配置模型验证

/app/models/user.rb

validates :password, length: {in: 8..20}
before_save {self.email = email.downcase}
validates :username, presence:true, length: {in: 6..20}
validates :email, presence:true, length: {in: 5..255}, format: {with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i}, uniqueness:{case_sensitive: false}
has_secure_password

3.3 controller

rails g controller User signin signup

/app/contorllers/application_controller.rb


  helper_method :current_user
def current_user
@current_user ||= session[:user_id] && User.find(session[:user_id])
end
def require_user
render json: {code:-1,info:'login_required'} unless current_user
end

/app/controllers/user_controller.rb

  def signup
@user = User.new(user_params)
if !@user.valid?
code = 0
data = @user.errors.messages
info = 'bad_for_reasons'
else
if @user.save
code = 1
info = 'success'
data = {userId:@user.id,username:@user.username}
else
code = 0
data = ''
info = 'reason_unknown'
end
end
render json: {code:code, info:info,data:data}
end def signin
@user = User.find_by_email(params[:email])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
render json: {code:1, info:'success',data:{userId:@user.id,username:@user.username}}
else
render json: {code:0,info:'bad'}
end
end def destroy # 注销
session[:user_id] = nil
render json: {code:1,info:'success'}
end private
def user_params
params.require(:user).permit(:username,:email,:password)
end

3.4 配置路由

格式: get 'url', to: 'controller#method'

3.5 启动

rails s

4. 部署

rails s -e production

可能会提示缺少SECRET_KEY_BASE

RAILS_ENV=production rake secret

/etc/profile
export SECRET_KEY_BASE=刚才生成的密钥
source /etc/profile

更多查看

https://www.cnblogs.com/yxi-liu/p/10331310.html