gpt4 book ai didi

ruby-on-rails - 如何从 ActiveRecord CollectionProxy 获取值?

转载 作者:数据小太阳 更新时间:2023-10-29 06:57:50 24 4
gpt4 key购买 nike

我在遍历集合属性以获取值时遇到问题。

这是我的代理

<ActiveRecord::Associations::CollectionProxy [#<Product id: 12, name: "test", cost_in_cents: 4400, created_at: "2014-10-31 17:18:58", updated_at: "2014-10-31 17:18:58", subscription: nil, product_type: "One Time">, #<Product id: 14, name: "aggg", cost_in_cents: 1400, created_at: "2014-10-31 17:28:19", updated_at: "2014-10-31 17:28:19", subscription: nil, product_type: "One Time">]>

我希望能够像这样遍历代理中的所有对象。

my_collection_proxy.each do |c| c.name end

但这似乎不起作用。如何获取代理中每个名称的值?

输出:

@order.products.each do |a| a.name end
=> [#<Product id: 12, store_front_id: 8, name: "test", cost_in_cents: 4400, created_at: "2014-10-31 17:18:58", updated_at: "2014-10-31 17:18:58", subscription: nil, product_type: "One Time">, #<Product id: 14, store_front_id: 8, name: "aggg", cost_in_cents: 1400, created_at: "2014-10-31 17:28:19", updated_at: "2014-10-31 17:28:19", subscription: nil, product_type: "One Time">]

我希望我的输出看起来像什么:

=> test
=> aggg

最佳答案

如果你想把所有的名字放到一个数组中,你应该使用 Enumerable#collect:

names = @order.products.collect(&:name)

关于ruby-on-rails - 如何从 ActiveRecord CollectionProxy 获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26681653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com