【问题标题】:can't cast ActiveRecord::Associations::CollectionProxy to text无法将 ActiveRecord::Associations::CollectionProxy 转换为文本
【发布时间】:2014-06-12 23:10:14
【问题描述】:

我正在尝试将数组保存到 Postgresql DB。听起来很简单。在成功完成条带付款后,我正在创建订单。

#stripe stuff (omitted)
Order.new(
:shipping_price => @order_preview.shipping_price,
:grand_total => @amount,
:cart => @cart,
:items => @cart.line_items
)
@order.save #error here

我收到一个错误:

can't cast ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_LineItem to text

如果我理解正确,rails 会告诉我它无法将数组保存到我的数据库的文本列中。为什么不呢?

这就是我的迁移的样子...

def change
   add_column :orders, :items, :text, array:true
end

感谢您的帮助...

谢谢

编辑:现在正在尝试创建一个仅包含 ID 的数组...

    :items => @cart.line_items.map { |l| l.product.id }

这给了我

PG::DatatypeMismatch at /charges
ERROR:  column "items" is of type integer[] but expression is of type text at character 249
HINT:  You will need to rewrite or cast the expression.

另外,在创建过程中出现错误时,我看到了正确的数组

items:[1, 2]

当然,我需要以哈希形式保存带有 ID 的数量,但是……我猜得从头开始。

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    @cart.line_items 不是一个数组(它是一个 ActiveRecord::Relation),@cart.line_items.to_a 不是一个字符串数组(它是一个 LineItems 数组)。

    您必须传递一个字符串数组才能将其存储在text[] 列中。因此,您要么需要确定适当的字符串,要么将列类型更改为其他类型。

    【讨论】:

    • 保存像@cart.line_items.to_a 这样的数组的列类型是什么?我的想法是我可以做 @order.items.each 做 |x|从视图
    • 你看过'hstore'吗,它允许你在postgres中保存json。有点像mongodb。
    • @Peege151 可能最明智的做法是存储 ID。但最后我检查了 ActiveRecord 不支持数组列中的关联,因此您必须自己连接所有内容。
    • 您的编辑中有语法错误::items => @cart.line_items.map {|l l.product.id|} 应该是 :items => @cart.line_items.map {|l| l.product.id}(最后一个管道被移除并放在“l”旁边)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多