我试图通过嵌套模型保存图像
**模型:
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#"}
Run Code Online (Sandbox Code Playgroud)
上市控制人:
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
Run Code Online (Sandbox Code Playgroud)
视图:
<%= form_for [@listing] do |f| %>
<%= f.fields_for :photos do |ph| %>
<%= ph.file_field :data %>
<% end%>
<%end%>
Run Code Online (Sandbox Code Playgroud)
这里我只提到了视图中的一个字段,但是我使用了很多字段,除了数据(图像)字段外,所有字段都保存在数据库中.
如果我在Photo模型中验证数据的存在,我得到了"照片不应该为空"的消息,尽管我上传了一张图片.