我有一个创建产品的 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 表单字段?
元芳怎么了
相关分类