在我的Rails 4 Controller操作中,我传递了以下参数:
{"user"=>{"email"=>"", "password"=>"[FILTERED]", "profile"=>{"birthday"=>nil, "gender"=>nil, "location"=>"", "name"=>""}}}
现在,从这些参数中,我希望创建两个对象:User
及其Profile
。
我尝试了以下代码的迭代,但是无法解决strong_params
问题:
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
方法是否曾经被击中。它几乎感觉就像我需要需要profile
在user_params
并处理。我也尝试过,将strong_params
方法更改为:
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) expected, got ActionController::Parameters(#70250792292140):
谁能对此有所启发?
试试这个:
user = User.new(user_params.except(:profile))
profile = user.build_profile(user_params[:profile])
您还可以使用Rails的嵌套属性。在这种情况下,配置文件参数将嵌套在key中:profile_attributes
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句