Skip to content

Instantly share code, notes, and snippets.

@tcopeland
Created December 31, 2017 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcopeland/05357dfd7eaf43a8152421f64b26fdaf to your computer and use it in GitHub Desktop.
Save tcopeland/05357dfd7eaf43a8152421f64b26fdaf to your computer and use it in GitHub Desktop.
$ cat db/migrate/* app/models/*.rb
class CreatePosts < ActiveRecord::Migration[5.1]
def change
create_table :posts do |t|
t.string :title
t.timestamps
end
end
end
class CreatePictures < ActiveRecord::Migration[5.1]
def change
create_table :pictures do |t|
t.string :name
t.timestamps
end
end
end
class CreateGalleries < ActiveRecord::Migration[5.1]
def change
create_table :galleries do |t|
t.string :name
t.timestamps
end
end
end
class CreateContentLinks < ActiveRecord::Migration[5.1]
def change
create_table :content_links do |t|
t.references :post, foreign_key: true
t.references :attachable, polymorphic: true
t.timestamps
end
end
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class ContentLink < ApplicationRecord
belongs_to :post
belongs_to :attachable, polymorphic: true
scope :pictures, -> { where(attachable_type: "Picture") }
scope :galleries, -> { where(attachable_type: "Gallery") }
end
class Gallery < ApplicationRecord
has_many :content_links, as: :attachable
end
class Picture < ApplicationRecord
has_many :content_links, as: :attachable
end
class Post < ApplicationRecord
has_many :content_links
end
# and then to query:
Loading development environment (Rails 5.1.4)
>> Post.first.content_links.pictures
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT $1 [["LIMIT", 1]]
ContentLink Load (0.3ms) SELECT "content_links".* FROM "content_links" WHERE "content_links"."post_id" = $1 AND "content_links"."attachable_type" = $2 LIMIT $3 [["post_id", 1], ["attachable_type", "Picture"], ["LIMIT", 11]]
=> #<ActiveRecord::AssociationRelation [#<ContentLink id: 1, post_id: 1, attachable_type: "Picture", attachable_id: 1, created_at: "2017-12-31 01:47:37", updated_at: "2017-12-31 01:47:37">]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment