如何设置控制器参数的默认值?

Zog*_*imu 3 ruby ruby-on-rails strong-parameters

我的数据库上有一个customers表,并且有一个名为“ last_updated_by”的列。我想在此字段中将当前用户名添加为纯文本。

我在我的应用程序上安装了devise,因此它为我提供了current_user参数。

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
Run Code Online (Sandbox Code Playgroud)

如何在控制器中设置一些默认值。

3li*_*t0r 5

由于您询问的是设置默认值,因此建议您使用ActionController :: Parameters#with_defaults方法,该方法只是ActionController :: Parameters#reverse_merge的(更具表达性)别名。

def customer_params
  params
    .require(:customer)
    .permit(:name, :last_updated_by)
    .with_defaults(last_updated_by: current_user.name)
end
Run Code Online (Sandbox Code Playgroud)

反向合并与普通合并具有相同的作用,唯一的区别是发生冲突的键会发生什么。普通合并使用提供的哈希值,而反向合并则首选原始哈希值而不是提供的哈希值。


Seb*_*lma 1

如果您需要last_updated_by将参数放入 customer_params( 的客户哈希键ActionController::Parameters)中,则:

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
Run Code Online (Sandbox Code Playgroud)

before_action 回调仅在执行创建操作之前在参数last_updated_by上添加新键。customer

请注意,无需修改 customer_params 即可允许它。


正如@JohanWentholt 所示,with_defaults这似乎是最好的方法。大胆试试吧。

等待OP选择正确答案。