我在has_one關聯模型上使用accep_nested_attributes_for。Rails 3.2:nested_attributes和has_one關聯,以兩種不同形式
我有兩個模型,一個用戶和一個配置文件。一個用戶有一個配置文件:
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在UsersController#更新
未定義的方法'名稱」的零:NilClass
我UsersController碼f或更新:
def update
@user = current_user
if @user.update_attributes(params[:user])
redirect_to home_path
else
render 'edit'
end
end
而且PARAMS是:
{"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'爲零,你會得到這個錯誤消息 - 所以這在沒有使用登錄時無法工作 – alony
是的,用戶已登錄,我有** before_filter:signed_in_user,只有:[:home,:update,:edit] **。 – Sebas
解決了!我對tmp文件夾有一些授權問題,用 'def cache_dir 「#{Rails.root}/tmp/uploads」 end' – Sebas