遇到以下模式:
params[:vehicle][:user_id]
params[:location][:user_id]
params[...etc...][:user_id]
什么语法允许创建将当前类作为参数内的符号输入的方法?例如
class VehiclesController
def edit
v = Vehicle.where('user_id = ? AND user_id = ?', params[:vehicle][:user_id], current_user.id).first
end
class LocationsController
def edit
l = Location.where('user_id = ? AND user_id = ?', params[:location][:user_id], current_user.id).first
end
你可以添加一个方法到ApplicationController:
class ApplicationController < ActionController::Base
private
def form_params
params[controller_name.singularize]
end
end
并在其他控制器中使用:
class VehiclesController < ApplicationController
def create
form_params # => #<ActionController::Parameters {"user_id"=>"1"} permitted: false>
end
end
对于允许的参数,可以是:
class ApplicationController < ActionController::Base
private
def form_params
params.require(controller_name.singularize).permit(permitted_params)
end
def permitted_params
[] # nothing is permitted by default
end
end
class VehiclesController < ApplicationController
def create
form_params # => #<ActionController::Parameters {"user_id"=>"1"} permitted: true>
end
private
# Override `permitted_params`
def permitted_params
# FIXME: Seems `user_id` is not needed when you have `current_user.id`.
# Besides, it is bad to expose current `user_id` in the form,
# because I can start messing with it and start submitting
# different ids in your forms; like a payment form, make someone
# else pay for my charges.
[:user_id]
end
end