【问题标题】:Nested inputs disappears when form gets reloaded重新加载表单时嵌套输入消失
【发布时间】:2013-06-24 03:08:14
【问题描述】:

在 Rails 应用程序中,我有一个创建产品页面,其中包含一个嵌套的照片表单。有验证可确保始终存在照片。但是,当我尝试提交没有照片的表单时,产品表单会重新呈现没有照片输入字段。

新产品页面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 :description
    = f.text_field :description
  %p
    = f.fields_for :photos do |fp|
      =fp.file_field :image
      %br
  %p.button
    = f.submit

产品控制器

class ProductsController < ApplicationController

  def new 
    @product = Product.new
    @photo = Photo.new
    4.times{ @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
      render "new", :notice => "Somehting went wrong!"
    end
end

  def edit
    @product = Product.find(params[:id])
    @photos_left = 4 - @product.photos.count 
    @new_photos = @photos_left.times.map{ @product.photos.build }
  end

  def update
    @product = Product.find(params[:id])
    if @product.update_attributes(params[:product])
      render "show", :notice => "Sale editted!"
    else
      render "edit", :notice => "Failed"
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    如果保存失败,则在创建中添加4.times{ @product.photos.build }

    更新您的创建操作,例如:

    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 } #you need to rebuild the photos here
          render "new", :notice => "Somehting went wrong!"
        end
    end
    

    更新操作也需要同样的改变

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      相关资源
      最近更新 更多