3
votes

I have been looking up different solutions for this problem but I can't seem to find any sort of conclusion as how best to deal with polymorphic relationships between Rails and Ember. In my case I have a polymorphic table called "todos" and one of the relationships to that table is called "patient". I get the todo records but they don't know what patient they are associated with. Any help into this would be greatly appreciated.

RAILS MODELS:

class Todo < ActiveRecord::Base
  belongs_to :todoable, polymorphic: true
end

class Patient < ActiveRecord::Base
  has_many :todos, as: :todoable
end

RAILS SERIALIZERS:

class TodoSerializer < ActiveModel::Serializer
  attributes :id, :content, :todoable_id, :todoable_type
end

class PatientSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :email
  has_many :todos
  embed :ids, include: true
end

EMBER DATA MODELS:

App.Todo = DS.Model.extend
  todoable_id: DS.attr 'number'
  todoable_type: DS.attr 'string'
  content: DS.attr 'string'
  patient: DS.belongsTo 'patient'

App.Patient = DS.Model.extend
  firstName: DS.attr 'string'
  lastName: DS.attr 'string'
  email: DS.attr 'string'
  todos: DS.hasMany 'todo', polymorphic: true, async: true
1
Why do you have both belongs_to :todoable and belongs_to :patient? - Sergio A.
@SergioA. Good catch. That shouldn't be there. Thank you. - sturoid

1 Answers

3
votes

That's actually a normal many-to-one relationship (ie. many Todos can belong to one Patient) and not a polymorphic relationship. If you said, "Todos can belong to a Patient or a Doctor or a Dog", then polymorphism might be the answer.

So, you can simply do:

class Todo < ActiveRecord::Base
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :todos
end

And in Ember:

App.Todo = DS.Model.extend
  patient: DS.belongsTo 'patient'

App.Patient = DS.Model.extend
  todos: DS.hasMany 'todo', async: true