I am running in a quite confusing error.
I'm trying to submit a Form with nested attributes - I'm whitelisting those via the strong_params in Rails 4.

Whenever I try to submit the Form, I'm getting this error:

ActiveRecord::UnknownAttributeError - unknown attribute: email:

My User Model has the following setup:

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

This gives me the following params:

{"email"=>"martin@teachmeo.com", "profile_attributes"=> {"first_name"=>"Martin", "last_name"=>"Lang", "website"=>"", "birthdate"=>"", "description"=>""}}

My User Model looks the following:

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

The Interesting thing is though, if I try to debug it via pry the @user.update_attributes(profile_params) works without any issues.

有帮助吗?

解决方案

You are calling

@user.profile.update_attributes!(profile_params)

This means you're updating attributes on an instance of Profile (I'll assume that's the model name), not User. As you've pointed out, :email is a column on the User model, not the Profile model. You're trying to apply a value for key :email to @user.profile, a column which Profile doesn't have, hence the ActiveRecord::UnknownAttributeError - unknown attribute: email: error.

I'm going to guess instead of the above you really want

@user.update_attributes!(profile_params)

since User has the :email attribute, and also likely has accepts_nested_attributes_for :profile set.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top