未知属性 - 属性存在

时间:2013-04-17 04:00:48

标签: ruby-on-rails ruby-on-rails-4 strong-parameters

我遇到了一个非常令人困惑的错误  我正在尝试提交一个带有嵌套属性的表单 - 我通过Rails 4中的strong_params将这些列入白名单。

每当我尝试提交表单时,我都会收到此错误:

  

ActiveRecord :: UnknownAttributeError - 未知属性:email:

我的用户模型具有以下设置:

user_controller.rb

def update
  if @user.profile.update_attributes!(profile_params)
    respond_to do |format|
      format.js
      format.html { redirect_to edit_user_path(@profile.user) }
    end
  end
end

private 

def profile_params
  params.require(:user).permit(:email,
                               {:profile_attributes => [:first_name, :last_name, :website, :birthdate, :description,
                                 {:address_attributes => [:city, :country, :phone]}]}

  )
end

这给了我以下参数:

  

{ “电子邮件”=> “中martin@teachmeo.com”,    “profile_attributes”=>     { “first_name的”=> “中马丁”,      “姓氏”=> “中郎”,      “网站”=> “中”,      “出生日期”=> “中”,      “描述”=> “中”}}

我的用户模型如下所示:

  

User(id:integer,email:string,password_digest:string,created_at:datetime,updated_at:datetime,auth_token:string)

有趣的是,如果我尝试通过pry调试它,@ user.update_attributes(profile_params)可以正常工作。

1 个答案:

答案 0 :(得分:3)

您正在致电

@user.profile.update_attributes!(profile_params)

这意味着您要更新Profile 实例的属性(我假设是型号名称) User 。正如您所指出的那样,:emailUser模型中的一列,不是 Profile模型。您正尝试将密钥:email的值应用于@user.profileProfile没有的列,因此ActiveRecord::UnknownAttributeError - unknown attribute: email:错误。

我会猜测而不是上面你真正想要的

@user.update_attributes!(profile_params)

由于User具有:email属性,并且可能还设置了accepts_nested_attributes_for :profile

相关问题