我正在尝试通过嵌套模型保存图像。
模型如下:
视图:
在这里,我只提到了视图中的一个字段,但我使用了很多字段,除了数据(图像)字段外,所有字段都保存在数据库中。
如果我验证照片模型中的数据存在性,即使我上传了图片,我也会得到“照片不能为空”的消息。
模型如下:
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%>
在这里,我只提到了视图中的一个字段,但我使用了很多字段,除了数据(图像)字段外,所有字段都保存在数据库中。
如果我验证照片模型中的数据存在性,即使我上传了图片,我也会得到“照片不能为空”的消息。