【问题标题】:Unknown Attribute - Attribute exists未知属性 - 属性存在
【发布时间】:2013-04-17 04:00:48
【问题描述】:

我遇到了一个非常混乱的错误。
我正在尝试提交具有嵌套属性的表单 - 我正在通过 Rails 4 中的 strong_params 将它们列入白名单。

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

ActiveRecord::UnknownAttributeError - 未知属性:电子邮件:

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

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

这给了我以下参数:

{"email"=>"martin@teachmeo.com", “profile_attributes”=> {"first_name"=>"马丁", "last_name"=>"Lang", "网站"=>"", "生日"=>"", "描述"=>""}}

我的用户模型如下所示:

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

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

【问题讨论】:

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


    【解决方案1】:

    你在打电话

    @user.profile.update_attributes!(profile_params)
    

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

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

    @user.update_attributes!(profile_params)
    

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

    【讨论】:

    • D'oh.. 是的。很有意义。重构后,我从 Profile Controller 复制了代码。谢谢!
    猜你喜欢
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 2015-02-07
    • 2019-03-22
    • 2016-04-25
    • 1970-01-01
    相关资源
    最近更新 更多