Default Controller Params
On occasion you may need to assign default values to the params required within a controller. For example, assume we’re working with todos and we want to assign a todo to the current user (by default, unless another user is specified), then I’ve usually seen some people handle default param values like this:
def todo_params
params
.require(:todo)
.permit(:subject, :description, :user_id)
.tap { |pms| pms.user_id ||= current_user.id }
endHowever, TIL that you can actually make use of a method called with_defaults:
def todo_params
params
.require(:todo)
.permit(:subject, :description, :user_id)
.with_defaults(user_id: current_user.id)
endMuch cleaner!
Also, with_defaults is defined for ActionController::Parameters and Hash. I find with_defaults much cleaner, and more intention revealing, than reverse_merge!