Skip to content

Instantly share code, notes, and snippets.

@ronanrodrigo
Last active December 18, 2015 11:49
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 ronanrodrigo/5778496 to your computer and use it in GitHub Desktop.
Save ronanrodrigo/5778496 to your computer and use it in GitHub Desktop.
Using polymorphic. With this, is possible to make a relation with any object.
# models/diet.rb
class Diet < ActiveRecord::Base
include Todoable
end
# models/prescription.rb
class Prescription < ActiveRecord::Base
include Todoable
end
# models/todo_item.rb
class TodoItem < ActiveRecord::Base
belongs_to :item, polymorphic: true
def item_attributes
self.item.attributes.keys - ["id", "created_at", "updated_at"]
end
end
# models/concerns/todoable.rb
module Todoable
extend ActiveSupport::Concern
included do
has_one :todo_item, as: :item
after_create :create_todo_item
end
def create_todo_item
TodoItem.create(item_type: self.class.name, item_id: self.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment