我在 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"}
任何帮助,将不胜感激。谢谢!!