Controller规则
app/controllers目录命名规则
支持命名空间,以module的方式组织
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