Skip to content

Conversation

PatKoperwas
Copy link

Restoring polymorphic has_one relationships errored because paranoia was
not correctly looking up the foreign_key.

Output from failing test -

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: parent_model_id: SELECT  "polymorphic_models".* FROM "polymorphic_models" WHERE ("polymorphic_models"."deleted_at" IS NOT NULL) AND (parent_model_id)  ORDER BY "polymorphic_models"."id" ASC LIMIT 1

The test sets up a PolymorphicModel, which has_many :parents. The
ParentModel then has a has_one relationship with PolymorphicModel. When
restoring, the foreign key is set as - self.class.name.to_s.underscore_id
which will be parent_model_id, instead of the :as option.

To fix,

If association is a has_one relationship with an :as option, it will
have a type attribute (see https://github.com/rails/docrails/blob/master/activerecord/lib/active_record/reflection.rb).

If it is present, that will be the type column on the polymorphic model.
The foreign key can be found as an attribute on association.

Restoring polymorphic has_one relationships errored because paranoia was
not correctly looking up the foreign_key.

Output from failing test -

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: parent_model_id: SELECT  "polymorphic_models".* FROM "polymorphic_models" WHERE ("polymorphic_models"."deleted_at" IS NOT NULL) AND (parent_model_id)  ORDER BY "polymorphic_models"."id" ASC LIMIT 1

The test sets up a PolymorphicModel, which has_many parents. The
ParentModel then has a has_one relationship with PolymorphicModel. When
restoring, the foreign key is set as - `self.class.name.to_s.underscore_id`
which will be parent_model_id, instead of the :as option.
If association is a has_one relationship with an :as option, it will
have a type attribute (see https://github.com/rails/docrails/blob/master/activerecord/lib/active_record/reflection.rb).

If it is present, that will be the type column on the polymorphic model.
The foreign key can be found as an attribute on association.
wioux added a commit that referenced this pull request Dec 4, 2014
Fix polymorphic has_one relationships
@wioux wioux merged commit d4a1f79 into wioux:rails4 Dec 4, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants