The following pattern is encountered:
params[:vehicle][:user_id]
params[:location][:user_id]
params[...etc...][:user_id]
what syntax allows the creation of a method that inputs the current class as the symbol within the param ? for example
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
CodePudding user response:
You can add a method to ApplicationController:
class ApplicationController < ActionController::Base
private
def form_params
params[controller_name.singularize]
end
end
and use it in other controllers:
class VehiclesController < ApplicationController
def create
form_params # => #<ActionController::Parameters {"user_id"=>"1"} permitted: false>
end
end
For permitted params, could be this:
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