为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪9158850 2023-05-11 14:42:03
我有一个创建产品的 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: :collectionend这是我拥有的控制器内部的方法: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)    endend这是控制器内部的新产品和创建产品方法:def new; enddef 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    endend 一切正常,所有字段都正确填充。我遇到的唯一问题是,当表单再次呈现时,由于验证错误,JSON 字段显示为空,即使它们已正确填充。即使表单返回验证错误,我如何保持填充 JSON 表单字段?
查看完整描述

1 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

问题是在页面加载时,您的下拉列表中没有可供选择的选项;因此表单无法选择正确的值。您需要像这样更新您的控制器:


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

        @categories = Category.all.order(:name)

        @subcategory = Subcategory.where(child_category_id: @product.child_category_id).order(:name)

        @child_subcategory = ChildSubcategory.where(subcategory_id: @product.subcategory_id).order(:name)

        format.html { render :new }

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

      end

    end

end


查看完整回答
反对 回复 2023-05-11
  • 1 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信