动态ActiveRecord关联(基于另一个模型)(Dynamic ActiveRecord Associations (based on another model))

系统教程 行业动态 更新时间:2024-06-14 17:03:54
动态ActiveRecord关联(基于另一个模型)(Dynamic ActiveRecord Associations (based on another model))

我想要做这样的事情:

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 end

But 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 end

There's something wrong with your code, it isn't doing what you expect it to.

"lowest_"+p.category+"_price".to_sym

Is 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

更多推荐

本文发布于:2023-04-24 14:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/3db61b3024200cd13b7fdcaca14a8768.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   动态   ActiveRecord   Dynamic   based

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!