【问题标题】:Ordering while Rails has_many with typecast String to decimal在 Rails has_many 中排序,将字符串类型转换为十进制
【发布时间】:2019-02-03 21:00:48
【问题描述】:

我将Size 模型与value 作为字符串。 我想通过将value 属性转换为十进制来订购sizes

has_many :sizes, -> {order 'value ASC'},这是按字母顺序排列的。

我试过has_many :sizes, -> {order 'value::integer ASC'},没有用。

谢谢

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-4 associations has-many


    【解决方案1】:

    我找到了解决方案。我们可以CAST下面的字段。

    has_many :sizes, -> { order 'CAST(value AS DECIMAL) ASC' }.

    【讨论】:

    • 听起来您使用了错误的列类型,强制转换有效,但我建议您考虑改用 DECIMAL 列。
    • @arieljuod,我正在存储像 10、10.5、11、11.5 这样的鞋码,所以使用字符串字段来存储它们。我需要将 10 存储为 10,而不是 10.0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 2016-03-06
    相关资源
    最近更新 更多