我对 Rails 很陌生,所以很可能这里有一个简单的概念,我只是不明白,但这就是正在发生的事情。
我有一个用户模型(由设计提供支持),每个用户都有自己的照片属性。我知道我可以将照片作为用户的一部分包含在内,但照片实际上是网站的核心内容,所以我更希望它们成为自己的表格。照片模型有一个回形针附件,用于处理实际的照片文件。
问题是:当我以用户身份上传照片时,一切都按计划进行,但由于某种原因,当我返回照片上传页面时,我刚刚上传的照片被删除了。我已经追踪到这行代码:
@photo = @user.build_photo
如果我不调用它,则上传表单会引发 nil 类错误,因为 @user.photo 不存在,但是当我调用它时,它会删除以前上传的照片,这很奇怪,因为就我知道,改变数据库的是创建函数,而不是构建。
这是服务器显示的内容:
在 2012-03-08 10:19:21 -0800 开始 GET "/settings" for 127.0.0.1 由 SettingsController#index 处理为 HTML 用户负载 (0.3ms) SELECT
users
.* FROMusers
WHEREusers
。id
= 6 LIMIT 1 照片负载 (0.3ms) SELECTphotos
.* FROMphotos
WHEREphotos
。user_id
= 6 LIMIT 1 (0.2ms) BEGIN [回形针] 安排删除附件。SQL (0.6ms) 从photos
WHERE中删除photos
。id
= 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