1

我在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"} 

任何幫助,將不勝感激。謝謝!!

+0

是你的用戶登錄嗎?我的意思是如果'current_user'爲零,你會得到這個錯誤消息 - 所以這在沒有使用登錄時無法工作 – alony

+0

是的,用戶已登錄,我有** before_filter:signed_in_user,只有:[:home,:update,:edit] **。 – Sebas

+1

解決了!我對tmp文件夾有一些授權問題,用 'def cache_dir 「#{Rails.root}/tmp/uploads」 end' – Sebas

回答

0

添加到您的用戶控制器

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

end 

爲了更好地瞭解發生了什麼嘗試寶石「better_errors」添加到您的Gemfile

gem "better_errors" 

你會得到一種控制檯,在那裏你可能類型

@user 

和作爲輸出,你會得到(無,或OBJ)。如果零,你絕對僞造這條線在新的行動

@user = User.new 

如果你使用divise爲自動。支持,重寫控制器喜歡這裏 Override devise registrations controller

+0

謝謝!!漂亮的寶石! – Sebas

0

@Andrey 作爲與HAS_ONE關係, @ user.profile.build不起作用,需要選擇以下,@ user.build_profile 有的告訴我如下: 「如果關聯是用has_one定義的,我們使用「build_association」函數,對於has_many,它應該是「association.build」。