用于类似查找查询的 DRY 实例变量

发布于 2024-12-04 07:09:37 字数 490 浏览 2 评论 0原文

也许这个问题已经有了答案,但我不确定要寻找什么。

我有一个页面,其中包含从 A 到 Z 的服装品牌列表,其中有一个用于迭代所有品牌的每个块。我想按字母拆分此列表,并在顶部有一个从 A 到 Z 的链接行,其中每个字母都会从页面跳到列表中的字母。然而,为了做到这一点,我只能想到为每个字母创建一个循环,旁边有 等,并为每个字母创建一个实例变量一。

我的问题是,如何避免控制器中出现 26 个不同的实例变量?

@Abrands = Product.where('brand LIKE ?', "A%")
@Bbrands = Product.where('brand LIKE ?', "B%")
@Cbrands = Product.where('brand LIKE ?', "C%")
etc.

这显然不是很干,有更好的方法吗?我仍然在寻找我的脚与铁轨,任何帮助将不胜感激!

Perhaps this question may have already been answered, but I am not sure what to search for.

I have a page with an A to Z list of clothing brands, which has an each block to iterate through them all. I would like to split this list out by letter, and have an A to Z row of links at the top, where each letter jumps down the page to their letter in the list. In order to do this however, I can only think of making an each loop for each letter, with <A NAME="A"> etc. next to it, and an instance variable for each one.

My question is, how do I avoid having 26 different instance variables in my controller?

@Abrands = Product.where('brand LIKE ?', "A%")
@Bbrands = Product.where('brand LIKE ?', "B%")
@Cbrands = Product.where('brand LIKE ?', "C%")
etc.

This is clearly not very DRY, is there a better way I could do this? I am still finding my feet with rails, any help would be much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

两相知 2024-12-11 07:09:37

这样的事情对你有用吗?

@products = Product.all.group_by{|product| product.brand.slice(0,1)}

这是一个很好的单行代码,只会发出 1 个查询。它将产生与其他用户的建议类似的哈希值。

Would something like this work for you?

@products = Product.all.group_by{|product| product.brand.slice(0,1)}

This is a nice one-liner that will only issue 1 query. It will result in a hash similar to other users' suggestions.

尴尬癌患者 2024-12-11 07:09:37
# Hash initialization to empty arrays
@brands = Hash.new { |h,k| h[k] = [] }

Product.all.each do |product|
  @brands[product.brand[0].upcase.to_sym] << product
end

它返回这样的哈希值:

{:A => [products for brands A*], :B => [products for brands B*], ...}

此方法的优点是只执行一次查询而不是 26 次查询。

# Hash initialization to empty arrays
@brands = Hash.new { |h,k| h[k] = [] }

Product.all.each do |product|
  @brands[product.brand[0].upcase.to_sym] << product
end

which returns a hash like this:

{:A => [products for brands A*], :B => [products for brands B*], ...}

This method has the advantage of doing only one query instead of 26.

心碎的声音 2024-12-11 07:09:37

这集 openrailscasts 对您有帮助吗?
非活动记录(字母产品)

Does this openrailscasts episode help you?
Non Active Record (Products by Letter)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文