mysql2 generating bad syntax on joins with polymorphic join table


I don’t know if this is an allowed design in rails, but it seems to me that it should be. I’ll first describe the models and then explain the (what I feel is, but want confirmation) error. An example repo with instructions on how to reproduce this can be found here: , I am using rails 4.0.2, (actual versions of all the gems can be found in Gemfile.lock).

I have a model called Center, and 2 models called Left and Right. Center has_many :lefts, and has_many :rights, both through a join model called Link, which belongs_to :center and belongs_to :linkable, polymorphic: true.

Center also has scopes to find centers with associated lefts, rights and a combination, called :with_left(left), :with_right(right) and :with_left_and_right(left, right), which join the required links and use a where(rights: {id:}) or the corresponding where clause.

The problem arises when I have this query:


which generate a StatementInvalid error in mysql2 (sqlite3 silently fails and I haven’t tested pg). The generated SQL is this:

SELECT COUNT(*) FROM centers INNER JOIN links right_links_centers_join ON right_links_centers_join.center_id = AND right_links_centers_join.linkable_type = ‘Right’ AND links.linkable_type = ‘Right’ INNER JOIN rights ON = right_links_centers_join.linkable_id INNER JOIN links ON = links.center_id WHERE links.linkable_id = 36 AND links.linkable_type = ‘Left’ AND links.linkable_type = ‘Left’ AND = 36

As you can see, the first reference to the links table gets aliased to right_links_centers_join, and the second reference doesn’t get an alias (because it’s not needed). The highlighted parts are extras that shouldn’t be there. The first one generates the error as the links table hasn’t been referenced by that name, and the second one is a repeat of the previous condition (in blue). If the second reference to links had been aliased, it would also generate an error (not seen in the example repo but in another case).

The red highlights, besides generating an error, are not needed, as the blue highlights cover the those conditions.

At first I thought that it could be from the source_type option in the has_many :lefts options in Control, but because the join table is polymorphic, rails complains that the source_type needs to be explicit.

Is this a bug? Or am I using the has_many in a wrong way? Even if I’m wrong, I think it should throw an error before generating a wrong SQL query.

Best regards,


I submitted a PR to address this issue,

Best regards,