是否可以在rails中使用create方法调用jQuery函数?
我有两个型号@product和@photo,照片嵌套在产品中。我正在使用this JQuery plugin处理照片上传,因为它为我提供了很好的预览效果。
问题是这个插件提供了一个“开始”按钮。单击时,它会在创建产品之前开始上载照片。所以我无法将照片连接到产品。我正在考虑删除“开始”按钮,只是在产品的创建操作中调用该函数。
这甚至可能吗?
这是一个好主意吗?
def create
@product = current_user.products.create(params[:product])
@photo = Photo.new(params[:photo])
respond_to do |format|
if @product.save
format.html {
render :json => [@photo.to_jq_image].to_json,
:content_type => 'text/html',
:layout => false
}
format.json { render json: {files: [@photo.to_jq_image]}, status: :created, location: @photo }
else
format.html { render action: "new" }
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
建立关联,以便Product
has_many :photos
和Photo
belongs_to:product`。然后在上传时创建照片而不提供产品ID。
当产品accepts_nested_attributes_for :photo
并且您将照片添加为fields_for
而不是单独的表单时,则在保存产品时,所有分配都可以。
参见
http://weblog.rubyonrails.org/2009/1/26/nested-model-forms/
http://railscasts.com/episodes/196-nested-model-form-part-1