gpt4 book ai didi

ruby-on-rails - 复杂类别下拉取决于存在的叶节点

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:01 25 4
gpt4 key购买 nike

我有这些关系

User
has_many :products
has_many :stores

Product
belongs_to :user
belongs_to :store
belongs_to :category

Store
belongs_to :user
has_many :products

Category
acts_as_nested_set
has_many :products

在主页(查看文件)中,我有一个类似于亚马逊的类别下拉列表:

 <ul id="site-category-dropdown">
<li class="has-dropdown">
<a href="#">
<span class="site-category-dropdown-link-span">
<span class="line-1">SHOP BY</span>
<span class="line-2">Category</span>
</span>

</a>
<ul class="dropdown dropdown-box-shadow">
<% Category.all.each do |root_cat| %>
<li class="has-dropdown site-category-dropdown-element">
<a href="#" class="site-category-dropdown-element-link">
<span class="term"><%= root_cat.name %></span>
</a>
<ul class="dropdown">
<% root_cat.children.each do |children| %>
<li><%= link_to children.name, category_path(id: children.id) %></li>
<% end %>
</ul>
</li>
<% end %>
</ul>
</li>
</ul>

这看起来像下图(悬停时显示根类别及其子类别) Site category dropdown

现在我在商店页面上,我想显示一个类似于网站下拉菜单的下拉菜单,但只针对商店正在销售的产品。
商店产品

Product 1 - (category_id: 46, store_id: 1, product_name: "Prada t-shirt")
Product 2 - (category_id: 47, store_id: 1, product_name: "Prada shoes")
Product 3 - (category_id: 47, store_id: 1, product_name: "Gucci shoes")
Product 4 - (category_id: 12, store_id: 1, product_name: "A classy Dining Table")
Product 5 - (category_id: 12, store_id: 1, product_name: "Kitchen stool")
Product 6 - (category_id: 12, store_id: 1, product_name: "Office Chair")

<br>
cateogory_id 46 is T-shirt in Fashion -> Men -> T-shirt
<br>
category_id 47 is Shoe in Fashion -> Men -> Shoe
<br>
category_id 12 is Furniture in Home -> Furniture
<br>

我正在为类别使用 awesome_nested_set gem ( https://github.com/collectiveidea/awesome_nested_set )
我可以使用以下方法映射数组中的所有 category_id:category_ids = @store.products.map(&:category_id)

我的问题是,我怎样才能建立一个类似于我上面显示的网站下拉列表的下拉列表,但仅限于这家商店销售的产品。请记住每个产品的 category_id 是叶类别的类别 ID,我如何从根类别重新创建下拉列表?使用我上面给出的商店产品,它应该看起来像这样: Store category drop down, only products sold by the store.

最佳答案

这可能是一个天真的实现,但我认为它可以解决问题。

# in your controller
@categories = find_root_categories @store.products.map(&:category_id)

def find_root_categories(leaf_categories)
leaf_categories.map { |node| find_root(node) }.uniq!
end

def find_root(leaf)
return leaf unless leaf.parent_id?
find_root(Category.find(leaf.parent_id))
end

然后您将像在原始帖子中那样遍历集合。这确实会产生 @engineersmnky 警告过的开销,因为您将进行大量的数据库调用。在调用 find_root 之前将所有类别缓存在实例变量中可能是个好主意:

# in the controller
@categories = Category.all

def find_root(leaf)
return leaf unless leaf.parent_id?
find_root(@categories.find(leaf.parent_id))
end

如果我对您的问题有任何误解,请告诉我!

关于ruby-on-rails - 复杂类别下拉取决于存在的叶节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043918/

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