1

我在 has_one 关联模型上使用accepts_nested_attributes_for。

我有两个模型,一个用户和一个配置文件。用户有一个配置文件:

class User < ActiveRecord::Base
  attr_accessible :name, :email,:profile_attributes
  has_one :profile
  accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
  attr_accessible :avatar
  belongs_to :user
  mount_uploader :avatar, AvatarUploader
end

我在编辑用户页面上有两个表单。一个更新主要用户属性(并且工作正常,下面未显示),然后是允许用户上传头像的一个:

<%= form_for @user, :html => {id: 'avatar_form' ,:multipart => true } do |f| %>
  <%= f.fields_for :profile do |builder| %>
  <%= builder.file_field :avatar %>
  <% end %>
  <%= f.submit %>
<% end %>

此提交不起作用,我收到此错误消息:

用户控制器中的 NoMethodError#update

nil:NilClass 的未定义方法“名称”

我的 UsersController 更新代码是:

def update
  @user = current_user
  if @user.update_attributes(params[:user])
    redirect_to home_path
  else
    render 'edit'
  end
end

参数是:

{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"YTpGnj9uIpybDAgf4c6pxMydY15ga5GZ++FBMe/6dV4=",
"user"=>{"profile_attributes"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x2303e08 @original_filename="test.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"user[profile_attributes][avatar]\";  filename=\"test.jpg\"\r\nContent-Type: image/jpeg\r\n",
"id"=>"3"}},
"commit"=>"Upload",
"id"=>"1"}

任何帮助,将不胜感激。谢谢!!

4

2 回答 2

0

@Andrey关于has_one关系,@user.profile.build不起作用,需要选择下面,@user.build_profile有人告诉我如下:“如果使用has_one定义关联,我们使用“build_association”函数。对于 has_many,它应该是“association.build”。

于 2014-10-10T08:14:11.450 回答
0

添加到您的用户控制器

def new
  @user = User.new
  @user.profile.build
  #or
  #@user.build_profile

end

为了更好地了解正在发生的事情,请尝试将 gem "better_errors" 添加到您的 Gemfile

gem "better_errors"

您将获得一种控制台,您可以在其中键入

@user

作为输出,您将得到(nil 或 obj)。如果为零,您肯定会在新动作中伪造这条线

@user = User.new

如果您将 divise 用于自动。支持,重写控制器,如这里 覆盖设计注册控制器

于 2013-05-06T06:40:05.750 回答