简体   繁体   English

Rails:在控制器中,将值添加到表单提交的参数中

[英]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. Emailname是通过表单提交的,但是在我为新用户编写行之前, position是在控制器中确定的。 How can I add position to my alpha_user_params ? 如何向我的alpha_user_params添加position

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: 如果position是用户的属性,则可以执行以下操作:

  @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. 这不需要您向alpha_user_params方法添加任何内容。 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. 由于position属性是由您的控制器生成的,因此不会由用户添加/修改,因此我建议您将此属性保留在控制器本身中。

user_params should only permit those attributes which will be input/modified by the user. user_params仅应允许用户输入/修改的那些属性。

I had a similar problem, I used before_create in the model: 我有一个类似的问题,我在模型中使用了before_create

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 您还可以使用其他回调,例如before_save ,请查看活动记录文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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