Reputation: 63627
In my "Users" db I have "email", "name", and "position".
Email
and name
are submitted through a form, but position
is determined in my controller before I write the row for the new user. How can I add position
to my alpha_user_params
?
def create
position = User.order("position DESC").first
# How can I add position to alpha_user_params????
@user = User.new(user_params)
if @user.save
# success stuff
else
# error stuff
end
end
private
def alpha_user_params
params.require(:alpha_user).permit(:email, :producer, :position)
end
Upvotes: 2
Views: 6210
Reputation: 3575
I had a similar problem, I used before_create
in the model:
class User < ApplicationRecord
before_create :get_position
private
def get_position
self.position = YourLibrary.position
end
This will add the position when the user is created. You can also use other callbacks like before_save
, check the active record documentation
Upvotes: 0
Reputation: 10754
if position
is an attribute for user, you can do:
@user = User.new(user_params)
@user.position = position
# @user.position = User.order("position DESC").first
if @user.save
# success stuff
else
# error stuff
end
This does not require you to add anything to your alpha_user_params
method. Since, the position
attribute is being generated by your controller and will not be added/modified by a user, I would advise you to keep this attribute inside your controller, itself.
user_params
should only permit those attributes which will be input/modified by the user.
Upvotes: 4