# Creating an object and uploading a file in a single form

**URL:** <https://www.ruby-forum.com/t/creating-an-object-and-uploading-a-file-in-a-single-form/133526>\
**Category:** Rails\
**Created:** [April 1, 2008, 10:49am UTC](https://www.ruby-forum.com/t/creating-an-object-and-uploading-a-file-in-a-single-form/133526 "2008-04-01T10:49:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [April 1, 2008, 10:49am UTC](https://www.ruby-forum.com/t/creating-an-object-and-uploading-a-file-in-a-single-form/133526/1 "2008-04-01T10:49:19Z")

</div>

Hi,

I got a single form to create an object that can have file attached  
(I’m using attachment\_fu). The problem is with create/update actions.  
Here’s how stripped create action looks like:

def create  
@news = News.new(params[:news])  
@news.asset = Asset.new(params[:asset]) if !params[:asset].blank?  
&& !params[:asset][:uploaded\_data].blank?

```
respond_to do |format|
  if @news.save
    format.html { redircet_to news_path }
  else
    format.html { render :action => "new" }
  end
end

```

end

In the form I check if @news.asset is not nil and then display a link  
to the asset (image).  
There are 2 problems:

- if the validation of news object fails, the asset is not saved, but  
@news.asset is not nil anymore, so I got link displayed to non-  
existing image
- if the validation of news object fails, the file upload fields are  
empty. If validation fails once again, the params[:asset] hash is  
empty - this forces user to select a file to upload every time  
validation fails

How to solve it? Should I save the asset even if validation of news  
object fails? If yes, how to automatically remove files that are not  
related to any news object (i.e. the image is saved, validation of  
news object fails and user simply closes the page without creating  
news object).

Thanks in advance for any tips
