This project is archived and is in readonly mode.
collection_singular_ids ignores association :include option
Reported by rob g | March 13th, 2011 @ 08:20 PM
We have a set of models similar to the following:
class User < ActiveRecord::Base
has_many :taggings, :include => :tag, :order => 'tags.name'
end
class Tagging < ActiveRecord::Base
belongs_to :user
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings
end
When attempting to get the set of tagging_ids:
User.first.tagging_ids
we get a StatementInvalid error
ActiveRecord::StatementInvalid:
Mysql2::Error: Unknown column 'tags.name' in 'order clause': SELECT `taggings`.id FROM `taggings` WHERE (`taggings`.user_id = 227792459) ORDER BY tags.name
I think I've tracked this to https://github.com/rails/rails/blob/3-0-stable/activerecord/lib/act... :
redefine_method("#{reflection.name.to_s.singularize}_ids") do
if send(reflection.name).loaded? || reflection.options[:finder_sql]
send(reflection.name).map { |r| r.id }
else
if reflection.through_reflection && reflection.source_reflection.belongs_to?
through = reflection.through_reflection
primary_key = reflection.source_reflection.primary_key_name
send(through.name).select("DISTINCT #{through.quoted_table_name}.#{primary_key}").map! { |r| r.send(primary_key) }
else
send(reflection.name).select("#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").except(:includes).map! { |r| r.id } # <===================
end
end
end
I've tried both removing the call to
except(:includes)
from line 1510 as well as expanding
the exceptions to include the association order:
send(reflection.name).select("#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").except(:includes, :order).map! { |r| r.id }
and either approach will result in valid SQL. Obviously, the latter approach generates a more performant query but the ids returned will no longer be in the order specified on the association which seems to be a reasonable tradeoff.
Comments and changes to this ticket
-
Aaron Patterson March 28th, 2011 @ 11:55 PM
- Assigned user set to Aaron Patterson
- Importance changed from to Low
-
Anatoliy Lysenko April 3rd, 2011 @ 12:45 PM
Rob was right,
This commit will revert fix from https://github.com/rails/rails/commit/3436fdfc12d58925e3d981e0afa61... , but tests is ok.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>