gpt4 book ai didi

ruby-on-rails - 模型关联返回的数组不是数组?

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

我们有一个看起来像这样的模型关联:

class Example < ActiveRecord::Base
has_many :others, :order => 'others.rank'
end

排名列为整型。这些特定模型的细节并不是很重要,因为我们发现其他模型之间的其他 has_many 关联也存在同样的问题。

我们还在 Enumerable 模块中添加了:

module Enumerable
def method_missing(name)
super unless name.to_s[0..7] == 'collect_'
method = name.to_s[8..-1]
collect{|element| element.send(method)}
end
end

这添加了一个 collect_id 方法,我们可以使用该方法从 ActiveRecord 对象数组中获取记录 ID 数组。

因此,如果我们使用普通的 ActiveRecord find :all,我们会得到一个很好的数组,然后我们可以在其上使用 collect_id,但如果我们使用 Example.others.collect_id,我们会得到

NoMethodError: undefined method `collect_id' for #<Class:0x2aaaac0060a0>

Example.others.class 返回“Array”,那么它是在说谎还是在混淆?

到目前为止,我们的解决方案是这样使用它:

Example.others.to_a.collect_id 

这行得通,但这看起来有点奇怪。为什么你必须这样做?

我们使用的是 Ruby 1.8.7 和 Rails 2.3.4

最佳答案

模型关联是代理,而不仅仅是简单的数组。

我建议您使用标准的 example.others.all.map(&:id) 而不是 example.others.all.collect_id 和您的补丁Rails 和 Ruby >=1.8.7 收集单个属性的方式。

关于ruby-on-rails - 模型关联返回的数组不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5278885/

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