0
votes

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 :|

1
I want to associate more object types on the future, withou creating new relation for each class... - Ronan
There is no way of creating further associations without explicitly declaring the relationship in the models. - zeantsoi
I have recently answered a similar question: stackoverflow.com/questions/17029659/… - Patrick Oscity

1 Answers

1
votes

Maybe you could try a different approach:

Diet.rb

has_many :todo_items, as: :todoable
after_create :create_todo_item

def create_todo_item
  todo_items.create
end

Prescription.rb

has_many :todo_items, as: :todoable
after_create :create_todo_item

def create_todo_item
  todo_items.create
end

and on every other model you need todos you can use the above code

In TodoItem.rb all you have to do is

belongs_to :todoable, polymorphic: true

And create the fields on TodoItem todoable_type and todoable_id

Looks a lot better IMO. Even this way it is possible to further refactoring it creating a module "todoable" and load it on every model you need, but it is a next step