问题描述
同样的问题 Rails的ActiveRecord的:总和,最大值和加入
除了得到奇怪的结果。
class CustomResumeline < ActiveRecord::Base
has_many :resumeline_words
end
class ResumelineWord < ActiveRecord::Base
belongs_to :custom_resumeline
end
CustomResumeline.joins(:resumeline_words).where(resumeline_words: {name: ["time", "data"]}).select('sum(resumeline_words.weight) as nb_votes').group('resumeline_words.custom_resumeline_id').order('nb_votes ASC')
结果
CustomResumeline Load (0.8ms) SELECT sum(resumeline_words.weight) as nb_votes FROM "custom_resumelines" INNER JOIN "resumeline_words" ON "resumeline_words"."custom_resumeline_id" = "custom_resumelines"."id" WHERE "resumeline_words"."name" IN ('time', 'data') GROUP BY resumeline_words.custom_resumeline_id ORDER BY nb_votes ASC
=> #<ActiveRecord::Relation [#<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, #<CustomResumeline id: nil>, ...]>
我的问题是,为什么我得到一个数组有一堆零号CustomResumelines?
My question is, why am I getting an array with a bunch of nil id CustomResumelines ?
感谢
推荐答案
根据您的查询,使用#选择
到
result = CustomResumeline.joins(:resumeline_words)...
结果
返回相关的对象,其中 ID
将Rails的添加为你使用#选择
,虽然你没有选择它。现在,您可以做
result
returns a relation object, where id
will added by Rails as you used #select
, although you have not selected it. You can do now
result. map { |rec| rec.nb_votes }
# will give array of `nb_votes` values.
从一些提示选择具体领域指南:
Client.select(viewable_by,锁定)
- 只选择viewable_by和锁定列。要小心,因为这也意味着你的初始化 模型对象的只有你所选择的领域。如果您试图访问一个字段是不是在初始化的记录,您将获得:加载ActiveModel :: MissingAttributeError:缺少属性:其中;属性&GT;
。其中,&LT;属性&GT;
是你要的属性。该 ID
方法不会提高的ActiveRecord :: MissingAttributeError
,所以用的协会工作时,只是要小心的,因为他们需要的ID的方法才能正常工作。
所以的 ID
方法不会提高的ActiveRecord :: MissingAttributeError
.. - 为什么?由于#选择
默认情况下,将其添加到通过将其与 ID
的值,生成每个模型对象零
。
So The id
method will not raise the ActiveRecord::MissingAttributeError
,.. -- Why ? As #select
add it by default it to each model object created by it with a value of id
as nil
.
这篇关于ActiveRecord的总和最大联接结果阵列与多个零IDS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!