我想要做这样的事情:
class Store < ApplicationRecord Product.select(:category).distinct do |p| has_one "lowest_"+p.category+"_price".to_sym, -> { where(category: p.category).order(price: :asc) }, class_name: "Product" end end但铁轨似乎忽略了线路在那里。 当我用硬编码数组替换Product.select(:category).distinct ,它工作正常,但它不是动态的。
我想这是一种初始化问题,但有没有解决方案? 我想我可以写一个初始化器,但我不知道如何在类创建后应用关联。 可能只是一个红宝石答案?
I'd like to do something like this:
class Store < ApplicationRecord Product.select(:category).distinct do |p| has_one "lowest_"+p.category+"_price".to_sym, -> { where(category: p.category).order(price: :asc) }, class_name: "Product" end endBut rails seems to ignore the lines are there. When I replace Product.select(:category).distinct with a hardcoded array it works fine, but then it's not dynamic.
I imagine this is some kind of initialization issue, but is there a solution? I'm thinking I can write an initializer, but I'm not sure how to apply an association after the class has been created. There may just be a straight ruby answer?
最满意答案
你的代码有问题,它没有达到你期望的效果。
"lowest_"+p.category+"_price".to_sym仅将"_price"转换为符号。
我也会使用pluck ,因为在这里你不需要你的Product模型。
请尝试这样做:
class Store < ApplicationRecord Product.pluck(:category).uniq do |category| has_one "lowest_#{category}_price".to_sym, -> { where(category: category).order(price: :asc) }, class_name: Product end endThere's something wrong with your code, it isn't doing what you expect it to.
"lowest_"+p.category+"_price".to_symIs only converting "_price" to a symbol.
I would also use pluck instead, since you don't need your Product model here.
Try doing this instead:
class Store < ApplicationRecord Product.pluck(:category).uniq do |category| has_one "lowest_#{category}_price".to_sym, -> { where(category: category).order(price: :asc) }, class_name: Product end end更多推荐
发布评论