如何在Rails控制器的嵌套项目中添加默认值?

问题描述 投票:0回答:1

在我的Rails 6应用程序的注册表单中,可以创建带有嵌套AccountUser

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

在这里在新的user上定义默认值的最佳方法是什么?

现在,我在注册表单中使用hidden_fields作为默认值,从而使它们公开可用。这当然是我想要的[[not,因为它很不安全。

有没有更好的方法来解决这个问题?

我知道有Rails' with_defaults方法,但到目前为止我无法在

嵌套项目上使用它。

ruby-on-rails ruby activerecord strong-parameters
1个回答
0
投票
尝试:

account_params[:users_attributes] = account_params[:users_attributes].with_defaults({ first_name: 'John', last_name: 'Smith'})

在创建动作的第一行中
© www.soinside.com 2019 - 2024. All rights reserved.