Last active
December 18, 2015 11:49
-
-
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.
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
# models/diet.rb | |
class Diet < ActiveRecord::Base | |
include Todoable | |
end |
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
# models/prescription.rb | |
class Prescription < ActiveRecord::Base | |
include Todoable | |
end |
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
# 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 |
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
# 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