accepts_nested_attributes_for未保存paperclip图像

3
我正在尝试通过嵌套模型保存图像。
模型如下:
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%>

在这里,我只提到了视图中的一个字段,但我使用了很多字段,除了数据(图像)字段外,所有字段都保存在数据库中。
如果我验证照片模型中的数据存在性,即使我上传了图片,我也会得到“照片不能为空”的消息。
1个回答

6

如果没有多部分表单,您将无法上传图像

在form_for声明中添加 :html => { :multipart => true } 来获得如下结果:

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

1
这个问题让我浪费了半天时间...即使一年前我也曾为此苦恼过。真是太蠢了... - Wouter A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接