2012-03-08 46 views
0

我對Rails很新,所以很可能這裏有一個簡單的概念,我只是沒有得到,但這裏是發生了什麼。當我調用構建時,Rails嵌套屬性被刪除

我有一個用戶模型(由Devise支持),每個用戶都有自己的照片屬性。我知道我可以將這張照片作爲用戶的一部分,但照片實際上是該網站的核心內容,所以我更喜歡他們是他們自己的桌子。照片模型有一個處理實際照片文件的回形針附件。

這裏的問題:一切都是按照我上傳照片的用戶計劃的工作,但由於某些原因,當我返回到照片上傳頁面,我剛剛上傳照片被刪除。我跟蹤它到這行代碼:

@photo = @ user.build_photo

如果我不叫,對於上傳的形式拋出一個零類錯誤,因爲@ user.photo不存在,但是當我打電話給它時,它會刪除先前上傳的照片,這很奇怪,因爲據我所知,它是創建函數來改變數據庫,而不是構建。

這裏是服務器的顯示:

開始GET 「/設置」 127.0.0.1在2012-03-08 10點19分21秒-0800 處理由SettingsController#指數HTML用戶負載(選擇usersid = 6極限1照片 負載(0.3ms)選擇photos。*從photos其中photosuser_id = 6限制1(0.2ms)開始[回形針]調度要刪除的附件。 SQL(0.6ms)DELETE FROM photos WHERE photosid = 20 [回形針]刪除附件。

這裏的一對夫婦我的模型和控制器:

class SettingsController < ApplicationController 
    def index 
     @user = current_user 
     @photo = @user.build_photo 
    end 
end 

<h1>Settings Page</h2> 
<%= image_tag @user.photo.the_photo.url(:medium) %> 
<%= form_for [@user, @photo], :html => { :multipart => true } do |f| %> 
    <%= f.file_field :the_photo %> 
    <%= f.submit %> 
<% end %> 


class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :photo_attribute 

    has_one :photo, :dependent => :destroy 
    accepts_nested_attributes_for :photo 
end 

class PhotosController < ApplicationController 
    def create 
     @user = current_user 
     @photo = @user.create_photo(params[:photo]) 
     redirect_to root_path 
    end 

    def update 
     @user = current_user 
     @photo = @user.photo 
     if @photo.update_attributes(params[:photo]) 
      redirect_to settings_path 
     else 
      redirect_to settings_path 
     end 
    end 

    def destroy 
    end 
end 

回答

1

正如你已經發現,調用@user.build_photo將刪除photouser如果已經存在。在這種情況下,您只需跳過build

@photo = @user.photo || @user.build_photo 
+0

天才,謝謝! – 2012-03-09 10:14:07