ActiveRecord Sum Max连接导致具有多个nil id的数组
与Rails activerecord相同的问题:sum,max和join
除了得到奇怪的结果。
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 [#, #, #, #, #, #, #, #, #, #, ...]>
我的问题是,为什么我得到一个带有一堆nil id CustomResumelines的数组?
谢谢
根据您的查询,您正在使用#select
result = CustomResumeline.joins(:resumeline_words)...
result
返回一个关系对象,其中id
将由Rails添加,因为您使用了#select
,尽管您没有选择它。 你现在可以做
result. map { |rec| rec.nb_votes } # will give array of `nb_votes` values.
选择特定字段指南中的一些提示:
Client.select("viewable_by, locked")
– 仅选择viewable_by和locked列。 要小心,因为这也意味着您只使用您选择的字段初始化 模型对象 。 如果您尝试访问不在初始化记录中的字段,您将收到:ActiveModel::MissingAttributeError: missing attribute:
。 其中是您要求的属性。
id
方法不会引发ActiveRecord::MissingAttributeError
,因此在使用关联时要小心,因为它们需要id方法才能正常运行。
所以id
方法不会引发ActiveRecord::MissingAttributeError
,.. – 为什么? 作为#select
,默认情况下将其添加到由它创建的每个模型对象,其值为nil
。