I need to create a todo list with any objects type. Objects that will be part of the list: Diet, Prescription and VeterinaryConsult.
Per hour i made: Keep the object class on object_type column, and when i will get the object, use the .send(TodoItem.x.object_type) method. This is the best way? I thought to use serialize option, but i don't how.
And for this, i create this structure:
Diet(id: integer, name: string, todo_item_id: integer, created_at: datetime, updated_at: datetime)
class Diet < ActiveRecord::Base
belongs_to :todo_item
end
Prescription(id: integer, name: string, todo_item_id: integer, created_at: datetime, updated_at: datetime)
class Prescription < ActiveRecord::Base
belongs_to :todo_item
end
TodoItem(id: integer, name: string, done_date: date, is_done: boolean, created_at: datetime, updated_at: datetime, object_type: string)
class TodoItem < ActiveRecord::Base
has_one :diet
has_one :prescription
def related
self.send(self.object_type)
end
end
On controllers i do:
class PrescriptionsController < ApplicationController
before_filter :create_todo_item, only: [:create]
def create
@prescription = Prescription.new(prescription_params)
@prescription.todo_item = @todo_item
...
end
class ApplicationController < ActionController::Base
def create_todo_item
@todo_item = TodoItem.new(object_type: params[:controller].singularize)
@todo_item.save
end
end
Sorry for my poor english :|