问题
Same Question as Rails activerecord : sum, max and joins
except getting strange results.
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')
Results
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>, ...]>
My question is, why am I getting an array with a bunch of nil id CustomResumelines ?
Thanks
回答1:
As per your query, you are using #select to
result = CustomResumeline.joins(:resumeline_words)...
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.
Some hints from Selecting Specific Fields guide :
Client.select("viewable_by, locked")- to select only viewable_by and locked columns. Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive:ActiveModel::MissingAttributeError: missing attribute: <attribute>. Where<attribute>is the attribute you asked for. Theidmethod will not raise theActiveRecord::MissingAttributeError, so just be careful when working with associations because they need the id method to function properly.
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.
来源:https://stackoverflow.com/questions/28683033/activerecord-sum-max-joins-results-in-array-with-multiple-nil-ids