rails controller 简单学习

Controller规则

app/controllers目录
命名规则

支持命名空间,以module的方式组织


Controller使用
class ApplicationController < ActionController::Base
end

class UsersController < ApplicationController

end


Controller中的实例方法

params
session
cookies
render
redirect_to

send_data

send_file
request
response


实例方法介绍

#params
获取HTTP请求中GET和POST的参数
可以使用Symbol和字符串的方式访问,比如params[:user], params["user"]


#send_data
def download
send_file "/file/to/download.pdf"
end

def download
send_data image.data, type: image.content_type
end


#request
request.fullpath
request.get?
request.headers
request.ip
request.body
etc.


#response
response.location
response.response_code
response.body=
etc.


Controller中的类方法

Filters
before_action
after_action
around_action


CSRF
protect_from_forgery


.helper_method方法介绍

这个方法的作用是让方法可以在view中能使用

class UserController <  class ApplicationController 

helper_method  :current_user

def current_user

@current_user  ||= User.find(session[:user_id])

end

end


Controller中打印log

Rails.logger
Rails.logger.info "debug info"
Rails.logger.info "Exception: ..."


Contorller中对异常的处理

rescue_from方法
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

private
def record_not_found
render plain: "404 Not Found", status: 404
end
end







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值