我有一个产品页面,允许用户添加一些文字和照片。产品是模型,照片也是。自然,每张照片都需要一个产品。所以我希望照片在提交产品之前显示缩略图。
我是不是该...
- 找到某种方法将这张照片存储在会话中(这在 Rails 中可行吗?)
- 或者,制作另一个模型来临时存储这张照片并使用 AJAX 立即加载它
PS我正在使用宝石'回形针'
编辑: new.html.haml
= form_for @product,:url => products_path, :html => {:multipart => true } do |f| 
  - if @product.errors.any?
    .error_messages
      %h2 Form is invalid
      %ul
        - for message in @product.errors.full_messages
          %li
            = message
  - if @photo.errors.any?
    .error_messages
      %h2 Image is invalid
      %ul
        - for message in @photo.errors.full_messages
          %li
            = message
  %p
    = f.label :name
    = f.text_field :name
  %p
    = f.label :description
    = f.text_field :description
  %p
    = f.fields_for :photos do  |fp|
      =fp.file_field :image
      %br
  %p.button
    = f.submit
产品控制器
  def new 
    @product = Product.new
    @photo = Photo.new
    # 4.times{ @product.photos.build }
    @product.photos.build
  end
  def create
  @product = current_user.products.new(params[:product])
  @photo = current_user.photos.new(params[:photo])
    if @product.valid?
      @product.save
      @photo.product_id = @product.id
      @photo.save
      render "show", :notice => "Sale created!"
    else
      # 4.times{ @product.photos.build }
      @product.photos.build
      render "new", :notice => "Somehting went wrong!"
    end
end