我已将模块保存在lib/rolify_roles.rb
module RolifyRoles
path = File.join(Rails.root, 'config', 'rolify_roles.yml')
@config = YAML.load_file(path)
def add_role(role, target = nil)
raise "Role is not defined!" if RolifyRoles.config[role].nil?
...
end
end
这个lib由models/user.rb
使用add_role
方法作为前缀。
然后在controllers/users_controller.rb
我有使用add_role
方法的方法:
def create_user_role
authorize User
role = params[:user][:rolify_role].to_sym
resource_type = params[:user][:resource_type]
resource_id = params[:user][:id]
resource = nil
resource = resource_type.constantize.find(resource_id) unless resource_type.blank? || resource_id.blank?
respond_to do |format|
if @user.add_role role, resource
format.html { redirect_to @user, notice: "Role #{role} was successfully added." }
format.json { render :show, status: :created, location: @user }
else
format.html { render :show }
format.json { render json: @call.errors, status: :unprocessable_entity }
end
end
# Add_role exceptions
rescue Exception => e
format.html { render :show }
format.json { render json: @call.errors, status: :unprocessable_entity }
end
我试图从控制器方法中的模块RolifyRoles
中捕获异常。
但是当引发异常(Role is not defined!
)时,它会在模块中结束,并且它不会由控制器处理。
User#add_role lib/rolify_roles.rb, line 31
如何在控制器中处理此行为?
我在控制器中尝试rescue
出现RecordNotFound
错误:
def create_user_role
authorize User
role = params[:user][:rolify_role].to_sym
resource_type = params[:user][:resource_type]
resource_id = params[:user][:id]
# Catch RecordNotFound doesn't work
begin
resource = nil
resource = resource_type.constantize.find(resource_id) if RolifyRoles.available_resources.include?(resource_type) && resource_id.present?
rescue ActiveRecord::RecordNotFound => e
format.html { render :show }
flash[:error] = e.message
end
end
当resource_type.constantize.find(resource_id)
无法找到记录时,它不会提升rescue
块。
Completed 500 Internal Server Error in 46ms (ActiveRecord: 3.2ms)
ActiveRecord::RecordNotFound - Couldn't find RequestComment with 'id'=1:
app/controllers/users_controller.rb:58:in `create_user_role'