gpt4 book ai didi

javascript - 在 "select_tag"select 上加载数据

转载 作者:行者123 更新时间:2023-11-27 23:40:35 25 4
gpt4 key购买 nike

我有标准电子商务模型:ProductCategoryProductOrderOrderItem

OrderItem 模型中,有 product_id 列。当用户创建订单并添加新订单项时,我想让他首先选择产品类别(在 select_tag 中),然后仅加载 f.collection_select :product_id 产品来自此类别。

现在我的 _order_item_fields.html.haml 看起来像这样:

.form-group
= label_tag 'product_category_id', 'Category'
= select_tag 'product_category_id', options_for_select(ProductCategory.all, 'id', 'name')

.form-group
= f.label :product_id, 'Product'
= f.collection_select :product_id, {# now it's empty}, :id, :name, {prompt: 'Choose category first'}

因此,我需要编写一些 JS 函数来根据所选类别加载数据。我不确定是否需要在 orders_controller 中编写 def 或者我可以在 orders.coffee 中作为从 选择时调用的函数>product_category_id 标签。

你能告诉我正确的道路吗?

感谢您的帮助!

最佳答案

我会编写一个 Controller 方法,根据产品类别返回正确的产品 ID 和名称,并通过 js 创建正确的选项。如果您有很多类别且有很多不同的产品 ID,那么这很有意义,因此应该能够很好地扩展。

Controller

# OrdersController

def product_options
category_id = params[:category_id]

render json: {
products: ProductCategory.find(category_id).products.pluck(:id, :name)
}
end

这将返回以下形式的 json:

{
products: [
[5, 'name of product with id 5'],
[12, 'name of product with id 12'],
...
]
}

路由

然后您必须为此添加一个路由条目:

# Routes
get '/route/to/product_options/:category_id', to: 'orders#product_options'

我认为您的 route 某处有resources :orders,但为了简洁起见,我现在只是创建了这样的路线 - 您可以修改您的路线!

咖啡

要获取此 json,您可以使用 jquery:

# orders.coffee

category_id = 5
$.get("/route/to/product_options/#{category_id}")

如果没有静态 category_id,只需监听类别选择器的 change 事件即可:

load_new_category = (category_id) ->
$.get("/route/to/product_options/#{category_id}")

$ -> # wait until page is loaded completely
$('[name="product_category_id"]').on 'change', ->
load_new_category $(@).val()

最后,您必须对返回的 json 执行一些操作来构建您的选项:

set_product_options = (products_json) ->
options_html = ''

for product_array in products_json.products
id = product_array[0]
name = product_array[1]

options_html += "<option value='#{id}'>#{name}</option>"

$('[name="product_id"]').html options_html

load_new_category = (category_id) ->
# attach it to `set_product_options` with `.done()`
$.get("/route/to/product_options/#{category_id}").done set_product_options

$ ->
$('[name="product_category_id"]').on 'change', ->
load_new_category $(@).val()

请仔细检查 jquery 选择器,以防出现问题(如果 Rails 确实生成此名称),但这应该为您提供一个良好的开始,以便根据您的需求实现和优化它。

(这是从头打出来的,希望里面没有错别字。)

关于javascript - 在 "select_tag"select 上加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com