2011-07-23 51 views
3

我试图通过嵌套模式将图像保存accepts_nested_attributes_for不节能回形针图像

**型号:

Listing 
    has_many:photos 
    accepts_nested_attributes_for :photos, :allow_destroy => true 

Photo 
    belongs_to:listing 
    has_attached_file :data, :styles=>{:featured => "88x63#", :search_result => "122x91#"} 

列表控制器:

def new 
    @listing = Listing.new 
    @listing.photos.build 
    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @listing } 
    end 
    end 

def create 
    @listing = Listing.new(params[:listing]) 
    if @listing.save 
     redirect_to(:action=>'index') 
    else 
     render :action => "new" 
    end 
end 

观点:

<%= form_for [@listing] do |f| %> 
    <%= f.fields_for :photos do |ph| %> 
     <%= ph.file_field :data %> 
    <% end%> 
<%end%> 

这里我只提到了视图中的一个字段,但是我使用了很多字段,并且除数据(图像)字段外,所有字段都保存在数据库中。

如果我在照片模型中验证了数据的存在,但我上传了一张图片后,我得到了“照片不应该是空的”消息。

回答

6

你将不能够除非你有一个多形式 添加上传图片:HTML => {:多=>真}声明的声明的form_for,所以你得到这样的事情

<%= form_for(@listing, :html => { :multipart => true }) do |f| %> 
+0

哦谢谢!现在它工作的很好... – arivarasan

+0

很高兴你得到它的工作 – jamesc

+1

这一天失去了半天...即使当我在一年前同样的问题挣扎。愚蠢的我... –