简体   繁体   中英

Rails: In a controller, add a value to the params submitted by a form

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM