Created
May 30, 2012 16:21
-
-
Save loginx/2837400 to your computer and use it in GitHub Desktop.
How to use make_flaggable with STI relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User.find(1).flag Tablet.find(1) | |
# => #<MakeFlaggable::Flagging id: 1, flaggable_type: "Device", flaggable_id: 1, flagger_type: "User", flagger_id: 1, reason: nil, created_at: "2012-05-30 16:16:23", updated_at: "2012-05-30 16:16:23"> | |
User.find(1).flagged? Tablet.find(1) | |
# MakeFlaggable::Flagging Load (0.4ms) SELECT "flaggings".* FROM "flaggings" WHERE "flaggings"."flagger_id" = 1 AND "flaggings"."flagger_type" = 'User' AND "flaggings"."flaggable_type" = 'Tablet' AND "flaggings"."flaggable_id" = 1 LIMIT 1 | |
# => false | |
# :rage: | |
######### | |
# If you look at the query, it inserted the `flaggable_type` as 'Device', but is searching for 'Tablet' | |
# Let's trick make_flaggable into looking for the proper type: | |
User.find(1).flagged? Tablet.find(1).becomes(Device) | |
# MakeFlaggable::Flagging Load (0.6ms) SELECT "flaggings".* FROM "flaggings" WHERE "flaggings"."flagger_id" = 1 AND "flaggings"."flagger_type" = 'User' AND "flaggings"."flaggable_type" = 'Device' AND "flaggings"."flaggable_id" = 1 LIMIT 1 | |
# => true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Device < ActiveRecord::Base | |
make_flaggable | |
end | |
class Tablet < Device | |
end | |
# Enable STI by creating a `type` column: | |
# rails g migration AddTypeToTablet type:string | |
# rake db:migrate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment