gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB \curl -sSL https://get.rvm.io | bash -s stable
rvm install 2.5.3html
yum install ruby-devmysql
gem install railssql
rails new ProjectName --api ( --skip-bundle ) 跳過bundle安裝數據庫
gemfile配置json
gem 'mysql2' # 若是是pg安裝'pg' gem 'rack-cors'
安裝: bundle install api
/config/database.ymlruby
default: &default adapter: mysql2 pool: 5 username: root password: pwdpwdpwd host: localhost charset: utf8 timeout: 5000 development: <<: *default database: databaseName test: <<: *default database: databaseName2 production: <<: *default database: databaseName3
/config/application.rbbash
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
! api模式默認不帶cookie
/config/application.rbsession
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
/app/controllers/application_controller.rb
include ActionController::Cookies include ActionController::RequestForgeryProtection # 放最後 private def set_csrf_cookie cookies["CSRF-TOKEN"] = form_authenticity_token end
rails g model User username:string email:string password_digest:string
/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
rails g controller User signin signup
/app/contorllers/application_controller.rb
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
格式: get 'url', to: 'controller#method'
rails s
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