用于类似查找查询的 DRY 实例变量
也许这个问题已经有了答案,但我不确定要寻找什么。
我有一个页面,其中包含从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样的事情对你有用吗?
这是一个很好的单行代码,只会发出 1 个查询。它将产生与其他用户的建议类似的哈希值。
Would something like this work for you?
This is a nice one-liner that will only issue 1 query. It will result in a hash similar to other users' suggestions.
它返回这样的哈希值:
此方法的优点是只执行一次查询而不是 26 次查询。
which returns a hash like this:
This method has the advantage of doing only one query instead of 26.
这集 openrailscasts 对您有帮助吗?
非活动记录(字母产品)
Does this openrailscasts episode help you?
Non Active Record (Products by Letter)