Rails:如果表单返回验证错误,则保持填充 JSON 表单字段

我有一个创建产品的 Rails 简单表单,表单中有以下三个字段,以便将产品与适当的类别相关联:


 <div class="form-group">

   <%= f.input :child_category_id, :collection => @categories.order(:name), :label_method => :name, :value_method => :id, label: "Category", :include_blank => "--Select Category--", input_html: { id: "first_dropdown" } %>

 </div>


 <div class="show_hide">

   <%= f.input :subcategory_id, :collection => [] || @subcategory.order(:name), :label_method => :name, :value_method => :id, label: false, :include_blank => "--Select Category--", input_html: { id: "second_dropdown" } %>

 </div>


 <div class="show_hide_third">

   <%= f.input :child_subcategory_id, :collection => [] || @child_subcategory.order(:name), :label_method => :name, :value_method => :id, label: false, input_html: { id: "third_dropdown" } %>

 </div>

这是路线:


resources :products, :path => "products/select_item", only: [:select_item] do

  get :select_item, on: :collection

end

这是我拥有的控制器内部的方法:


def select_item

  if params[:child_category_id].present?

    @subcategory = Subcategory.where(child_category_id: params[:child_category_id])

    render :json => @subcategory.order(:name)

  end

  if params[:subcategory_id].present?

    @child_subcategory = ChildSubcategory.where(subcategory_id: params[:subcategory_id])

    render :json => @child_subcategory.order(:name)

    end

end

这是控制器内部的新产品和创建产品方法:


def new; end


def create

  @product = Product.new(product_params)

    respond_to do |format|

      if @product.save

        format.html { redirect_to root_path }

        format.json { render :new, status: :created, location: @product }

        flash[:success] = "Product was successfully added."

      else

        format.html { render :new }

        format.json { render json: @product.errors, status: :unprocessable_entity }

      end

    end

end 



一切正常,所有字段都正确填充。我遇到的唯一问题是,当表单再次呈现时,由于验证错误,JSON 字段显示为空,即使它们已正确填充。即使表单返回验证错误,我如何保持填充 JSON 表单字段?


慕田峪9158850
浏览 102回答 1
1回答

元芳怎么了

问题是在页面加载时,您的下拉列表中没有可供选择的选项;因此表单无法选择正确的值。您需要像这样更新您的控制器:def create&nbsp; @product = Product.new(product_params)&nbsp; &nbsp; respond_to do |format|&nbsp; &nbsp; &nbsp; if @product.save&nbsp; &nbsp; &nbsp; &nbsp; format.html { redirect_to root_path }&nbsp; &nbsp; &nbsp; &nbsp; format.json { render :new, status: :created, location: @product }&nbsp; &nbsp; &nbsp; &nbsp; flash[:success] = "Product was successfully added."&nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; @categories = Category.all.order(:name)&nbsp; &nbsp; &nbsp; &nbsp; @subcategory = Subcategory.where(child_category_id: @product.child_category_id).order(:name)&nbsp; &nbsp; &nbsp; &nbsp; @child_subcategory = ChildSubcategory.where(subcategory_id: @product.subcategory_id).order(:name)&nbsp; &nbsp; &nbsp; &nbsp; format.html { render :new }&nbsp; &nbsp; &nbsp; &nbsp; format.json { render json: @product.errors, status: :unprocessable_entity }&nbsp; &nbsp; &nbsp; end&nbsp; &nbsp; endend
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript