我有Rails 5.2.3,并且使用祖先宝石。
我希望用户为汽车零件创建报价,但是在新表格中,我希望能够选择零件所属的类别/子类别,然后填写我拥有的其他详细信息,然后提交表单以创建要约。假设有人想卖刹车片。
所以首先必须选择类别/子类别,依此类推...
(因此,当他选择“汽车”时,第二个下拉列表应显示“汽车”的子类别)
例如:
Dropdown1:汽车
Dropdown2:刹车
因此,选择Brakes后,他可以填写其他字段并提交。
我所拥有的:
我已经在控制台中创建了Category / Subcategory,只是为了使其工作: 例如
car = Category.create!(name: "Car")
brakes = Category.create!(name: "Brakes", parent: car)
#category.rb
class Category < ApplicationRecord
has_ancestry cache_depth: true
has_many :parts
end
#part.rb
class Part < ApplicationRecord
belongs_to :category
end
#categories_controller.rb
class CategoriesController < ApplicationController
def select_item
category = @category.find(params[:category_id])
render json: category.children
end
end
#app/inputs/fake_select_input.rb
class FakeSelectInput < SimpleForm::Inputs::CollectionSelectInput
def input(wrapper_options = nil)
label_method, value_method = detect_collection_methods
merged_input_options =
merge_wrapper_options(input_html_options,
wrapper_options).merge(input_options.slice(:multiple,
:include_blank, :disabled, :prompt))
template.select_tag(
attribute_name,
template.options_from_collection_for_select(collection,
value_method, label_method, selected:
input_options[:selected], disabled:
input_options[:disabled]),
merged_input_options
)
end
end
#routes.rb
Rails.application.routes.draw do
resources :parts
resources :categories, only: [] do
get :select_item, on: :collection
end
end
#application.js
$('#first-dropdown').on('change', function() {
$.ajax({
url: 'categories/select_item?category_id=' + $(this).val(),
dataType: 'json',
success: function(data) {
var childElement = $('#second-dropdown');
childElement.html('');
data.forEach(function(v) {
var id = v.id;
console.log(id);
var name = v.name;
childElement.append('<option value="' + id + '">' + name + '</option>');
});
}
});
});
#views/parts/new.html.haml
= simple_form_for @part do |f|
= f.input :parent_category_id, as: :fake_select, collection: Category.roots, input_html: { id: 'first-dropdown' }, label: "Category"
= f.input :category_id, collection: [], input_html: { id: 'second-dropdown' }, label: "Subcategory"
= f.input :title
= f.input :part_number
= f.input :price, label: "Price"
= f.input :condition, label: "Condition", prompt: "-", collection:([["New", "New"], ["Used", "Used"], ["Rebuilt", "Rebuilt"], ["Aftermarket/Imitation", "Aftermarket/Imitation"]])
= f.input :make, label: "Part Make"
= f.input :part_model_name, label: "Part Model"
= f.input :description
.form-group
= f.button :submit, class: "btn btn-primary btn-block"
问题在于Dropdown1的类别为“汽车”,而Dropdown2为空。 有人可以帮我还是向我推荐一些东西?我没有其他任何错误,我无法继续前进。 (我使用祖先,因为以后我将添加许多类别/子类别/子类别等)