I have a customers table on my database and a column named as "last_updated_by" . I want to add current users name as a plain text in this field.
I got devise installed on my app so it gives me the current_user parameter.I tried to add current_user.name to the customers_controllers permitted parameters but it did not worked.
1-
def customer_params
params.require(:customer).permit(:name, :last_updated_by=>current_user.name)
end
2-
def customer_params
params[:last_updated_by] = current_user.name
params.require(:customer).permit(:name, :last_updated_by)
end
3-
def customer_params
last_updated_by = current_user.name
params.require(:customer).permit(:name, :last_updated_by=>current_user.name)
end
How can i set some default values in controller.
If you need the last_updated_by
param to go within the customer_params (customer hash key for ActionController::Parameters
), then:
before_action :set_last_updated_by_param, only: :create
private
def set_last_updated_by_param
params[:customer][:last_updated_by] = params.dig(:customer, :name)
end
The before_action callback adds the new key last_updated_by
on the customer
params only before the create action is executed.
Notice, no need to modify the customer_params to permit it.
As showed by @JohanWentholt, with_defaults
seems to be the best way. Go for it.
Waiting the OP chooses the correct answer.