本文介绍了使用 strong_params 在 Rails 4 控制器中创建两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Rails 4 控制器操作中,我传递了以下参数:

In my Rails 4 Controller action, I'm passing the following params:

{"user"=>{"email"=>"", "password"=>"[FILTERED]", "profile"=>{"birthday"=>nil, "gender"=>nil, "location"=>"", "name"=>""}}}

现在我希望从这些参数中创建两个对象:User 和它的 Profile.

Now from those params I'm hoping to create two objects: User and its Profile.

我尝试了以下代码的迭代,但无法通过strong_params 问题:

I've tried iterations of the following code but can't get passed strong_params issues:

def create
  user = User.new(user_params)
  profile = user.build_profile(profile_params)

  ...
end

  private

    def user_params
      params.require(:user).permit(:email, :password)
    end

    def profile_params
      params[:user].require(:profile).permit(:name, :birthday, :gender, :location)
    end

由于上面的代码抛出了一个 Unpermitted parameters: profile 错误,我想知道 profile_params 方法是否会被击中.感觉就像我需要在 user_params 中要求 profile 并处理它.我也试过了,将我的 strong_params 方法更改为:

Since the code above throws an Unpermitted parameters: profile error, I'm wondering if the profile_params method is even ever getting hit. It almost feels like I need to require profile in user_params and handle that. I've tried that as well, changing my strong_params methods to:

def create
  user = User.new(user_params)
  profile_params = user_params.delete(:profile)
  profile = user.build_profile(profile_params)

  ...
end

private

  def user_params
    params.require(:user).permit(:email, :password, profile: [:name, :birthday, :gender, :location])
  end

但我得到 ActiveRecord::AssociationTypeMismatch - Profile(#70250830079180) 预期,得到 ActionController::Parameters(#70250792292140):

有人能解释一下吗?

推荐答案

试试这个:

user = User.new(user_params.except(:profile))
profile = user.build_profile(user_params[:profile])

您还可以使用 Rails 的嵌套属性.在这种情况下,配置文件参数将嵌套在键 :profile_attributes 中.

You could also use Rails' nested attributes. In that case, the profile params would be nested within the key :profile_attributes.

这篇关于使用 strong_params 在 Rails 4 控制器中创建两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:22