Created
April 11, 2014 22:43
-
-
Save jeremy/10507535 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'active_record' | |
ActiveRecord::Base.logger = Logger.new($stdout) | |
ActiveRecord::Base.establish_connection adapter: 'mysql2', database: 'activerecord_unittest' | |
ActiveRecord::Base.connection.instance_eval do | |
create_table(:taggings, :force => true) do |t| | |
t.belongs_to :taggable, polymorphic: true | |
t.belongs_to :tag | |
end | |
create_table(:tags, :force => true) { |t| t.string :name } | |
create_table(:people, :force => true) { |t| t.string :name } | |
end | |
class Tagging < ActiveRecord::Base | |
belongs_to :tag | |
belongs_to :taggable, polymorphic: true | |
end | |
class Tag < ActiveRecord::Base | |
has_many :taggings, as: :taggable | |
end | |
class Person < ActiveRecord::Base | |
scope :tagged_with, ->(id) { joins(:taggings).where(taggings: { tag_id: id }) } | |
has_many :taggings, as: :taggable | |
has_many :tags, through: :taggings | |
end | |
tag = Tag.create! name: 't' | |
p = Person.create! name: 'p' | |
Tagging.create! tag: tag, taggable: p | |
Person.tagged_with(tag.id).update_all name: "rofl" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sqlite3:
mysql2: