ruby-on-rails - 如何为 Rails 控制器中的嵌套项添加默认值?
问题描述
在我的 Rails 6 应用程序的注册表单中,可以创建一个Account
带有嵌套的。User
class AccountsController < ApplicationController
def new
@account = Account.new
@account.users.build(
:owner => true,
:language => "FR"
)
end
def create
@account = Account.new(account_params)
if @account.save
redirect_to root_url, :notice => "Account created."
else
render :new
end
end
private
def account_params
safe_attributes = [
:name,
:users_attributes => [:first_name, :last_name, :email, :password, :owner, :language]
]
params.require(:account).permit(*safe_attributes)
end
end
在 new here上定义默认值的最佳方法是什么?user
现在,我hidden_fields
在我的注册表单中使用默认值,从而使它们公开可用。这当然不是我想要的,因为它非常不安全。
有没有更好的方法来处理这个问题?
我知道有Rails 的 with_defaults方法,但到目前为止我无法让它在嵌套项目上工作。
解决方案
尝试:
account_params[:users_attributes] = account_params[:users_attributes].with_defaults({ first_name: 'John', last_name: 'Smith'})
在创建动作的第一行
推荐阅读
- c# - 是否可以在 Android 上保持 WebView 音频在后台运行?
- c - 在 C 中显示大双打
- c - fts_read 和 fts_children 不是线程安全的吗?
- c# - 不将小时、分钟和秒识别为有效日期格式的一部分
- javascript - 使用议程时出现 UnhandledPromiseRejectionWarning
- ios - iPhone 6s 上不支持 Unity 的着色器
- c - 什么是处理 strcpy 的返回类型的正确方法
- php - 我的数据库的库存计数一直从 28 开始?
- reactjs - 反应参考电流为 NULL
- c++ - 从混合数据文件中读取将项目添加到字符串数组和二维 int 数组 C++