This project is archived and is in readonly mode.

#2375 ✓duplicate
Bartosz Pietrzak

SQL syntax error while executing count with has_many :through and named_scopes

Reported by Bartosz Pietrzak | March 30th, 2009 @ 11:42 AM | in 2.x

Appl.rb:


  named_scope :confirmed, :conditions => {:state => "confirmed"}
  has_many :tags, :through => :taggings
  has_many :taggings, :dependent => :destroy

Tag.rb:


  has_many :appls, :through => :taggings

And now in script/console:


= Tag.find 65
  Tag Load (0.6ms)   SELECT * FROM `tags` WHERE (`tags`.`id` = 65) 
=> #<Tag id: 65, name: "DO DUPY!!!", created_at: "2009-03-04 11:11:15", updated_at: "2009-03-04 11:11:15", company_id: 1, color: "f1f5ec", font_color: "006633", taggings_count: 20>
>> t.appls.size
  SQL (0.7ms)   SELECT count(*) AS count_all FROM `appls` INNER JOIN `taggings` ON `appls`.id = `taggings`.appl_id WHERE ((`taggings`.tag_id = 65)) 
=> 20
>> t.appls.confirmed.size
  SQL (0.0ms)   Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) AS count_appls_all FROM `appls` INNER JOIN `taggings` ON `appls`.id = `taggin' at line 1: SELECT count(`appls`.*) AS count_appls_all FROM `appls` INNER JOIN `taggings` ON `appls`.id = `taggings`.appl_id WHERE (((`appls`.`state` = 'confirmed') AND ((`taggings`.tag_id = 65))) AND ((`taggings`.tag_id = 65))) 
ActiveRecord::StatementInvalid: Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) AS count_appls_all FROM `appls` INNER JOIN `taggings` ON `appls`.id = `taggin' at line 1: SELECT count(`appls`.*) AS count_appls_all FROM `appls` INNER JOIN `taggings` ON `appls`.id = `taggings`.appl_id WHERE (((`appls`.`state` = 'confirmed') AND ((`taggings`.tag_id = 65))) AND ((`taggings`.tag_id = 65))) 

While t.appls.confirmed.to_a.size gives 20.

Error is in count(appls.), when I change it manually to count() it works well and gives the expected result.

Comments and changes to this ticket

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>

Pages