2012-03-08 72 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