Skip to content

Instantly share code, notes, and snippets.

@DriesS
Last active December 31, 2015 05:49
Show Gist options
  • Select an option

  • Save DriesS/7943084 to your computer and use it in GitHub Desktop.

Select an option

Save DriesS/7943084 to your computer and use it in GitHub Desktop.
Polymorphic associations
u.recently_viewed_items
[#<ListItem id: 2459209, list_id: 655831, listable_type: "Product", listable_id: 84303, created_at: "2013-12-13 11:19:07", updated_at: "2013-12-13 11:19:07">, #<ListItem id: 2459208, list_id: 655831, listable_type: "Product", listable_id: 84543, created_at: "2013-12-13 11:19:02", updated_at: "2013-12-13 11:19:02">, #<ListItem id: 2459207, list_id: 655831, listable_type: "Product", listable_id: 84403, created_at: "2013-12-13 11:18:57", updated_at: "2013-12-13 11:18:57">, #<ListItem id: 2459206, list_id: 655831, listable_type: "Product", listable_id: 84553, created_at: "2013-12-13 11:18:51", updated_at: "2013-12-13 11:18:51">, #<ListItem id: 2459205, list_id: 655831, listable_type: "Product", listable_id: 84413, created_at: "2013-12-13 11:18:45", updated_at: "2013-12-13 11:18:45">, #<ListItem id: 2459203, list_id: 655831, listable_type: "Product", listable_id: 84373, created_at: "2013-12-13 11:01:49", updated_at: "2013-12-13 11:18:25">]
require_dependency 'list'
class List::Favorite < List
end
class List < ActiveRecord::Base
belongs_to :user
has_many :list_items
end
class ListItem < ActiveRecord::Base
belongs_to :list
belongs_to :listable, :polymorphic => true
end
require_dependency 'list'
class List::RecentlyViewed < List
default_scope -> { order("updated_at desc") }
end
class User < ActiveRecord::Base
has_one :favorite, :class_name => "List::Favorite"
has_one :recently_viewed, :class_name => "List::RecentlyViewed"
has_many :recently_viewed_items, :through => :recently_viewed, :source => :list_items
has_many :favorite_items, :through => :favorite, :source => :list_items
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment