【发布时间】:2012-11-23 05:40:54
【问题描述】:
我在 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 %>
此提交不起作用,我收到此错误消息:
UsersController#update 中的 NoMethodError
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"}
任何帮助将不胜感激。谢谢!!
【问题讨论】:
-
您的用户登录了吗?我的意思是如果
current_user为 nil,您将收到此错误消息 - 所以当没有使用登录时这将无法工作 -
是的,用户已登录,我有 before_filter :signed_in_user,只有:[:home, :update, :edit]。
-
解决了!我在 tmp 文件夹中遇到了一些授权问题,将其更改为
def cache_dir "#{Rails.root}/tmp/uploads" end
标签: ruby-on-rails ruby ruby-on-rails-3.2 nested-attributes form-for