我有两个模型User
和Attachment
其中User has many Attachments
和Attachment belongs to User
我正在尝试使用Carrierwave实现文件上传/下载服务。
这是我保存上传的方式:
def create
uploader = LauncherUploader.new
@user = User.find(params[:user_id])
@attachment = Attachment.new(params[:attachment => {:file => [ :original_filename ]}])
@attachment.name = params[:attachment][:file].original_filename
@attachment.format = params[:attachment][:file].content_type
@attachment.user_id = @user.id
@attachment.save
uploader.store!(params[:attachment][:file])
redirect_to user_attachments_path, notice: "The file #{@attachment.name} was uploaded"
end
这就是我试图删除文件的方式:
def destroy
@user = User.find(params[:user_id]) or not_found
@attachment = @user.attachments.find(params[:id])
@attachment.destroy
uploader = LauncherUploader.new
uploader.remove_attachment!(@attachment)
redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been deleted."
end
我的上传者被称为Launcher
。当前destroy
方法从数据库中删除记录,但不从内存中删除记录。需要做些什么来纠正这种行为?
修改
这是当前附件的显示方式
[VIEW]
<% @attachments.each do |attachment| %>
<tr>
<td><%= attachment.name %></td>
<td><%= attachment.format %></td>
<td><%= link_to 'Download Link', :action => 'download' , :id => attachment.id %></td>
<td><%= button_to 'Delete', user_attachment_path(params[:user_id], attachment),
method: :delete,
data: { confirm: 'Are you sure?' }, :class => 'btn' %></td>
</tr>
<% end %>
[CONTROLLER]
def index
@attachments = Attachment.where(:user_id => params[:user_id])
end
任何已删除的文件都不会出现在此列表中。但继续存在于上传文件夹中。