【问题标题】:Ember and Rails polymorphic relationshipsEmber 和 Rails 多态关系
【发布时间】:2014-11-28 11:51:58
【问题描述】:

我一直在为这个问题寻找不同的解决方案,但我似乎找不到任何关于如何最好地处理 Rails 和 Ember 之间的多态关系的结论。就我而言,我有一个名为“todos”的多态表,与该表的其中一个关系称为“患者”。我得到了待办事项记录,但他们不知道他们与什么病人有关。对此的任何帮助将不胜感激。

铁路模型:

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

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

RAILS 序列化器:

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 数据模型:

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

【问题讨论】:

  • 你为什么同时拥有belongs_to :todoablebelongs_to :patient
  • @SergioA。接得好。那不应该在那里。谢谢。

标签: ember.js ember-data


【解决方案1】:

这实际上是一个正常的多对一关系(即许多 Todos 可以属于一个患者)而不是多态关系。如果您说“Todos 可以属于患者、医生或狗”,那么多态性可能就是答案。

所以,你可以这样做:

class Todo < ActiveRecord::Base
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :todos
end

在 Ember 中:

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

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

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    相关资源
    最近更新 更多