Ember递归父子关系错误

时间:2014-05-20 19:33:18

标签: ruby-on-rails ember.js ember-data relationship

我有一个rails后端,我试图制作一个Ember.js管理面板。基本上有些类别可以是其他类别的父母,类别可以有很多"贴纸"但"贴纸"也可以有很多类别。请考虑后端结构不可变(我可以摆弄序列化器,但那就是它)。这是我的序列化器:

类别型号:

class Category < ActiveRecord::Base
  has_many :parent_cats, class_name: "CatToCat",foreign_key: "child_id"
  has_many :children_cats, class_name: "CatToCat",foreign_key: "parent_id"

  has_many :parents, through: :parent_cats
  has_many :children, through: :children_cats
end

类别到类别模型:

class CatToCat < ActiveRecord::Base
  belongs_to :parent, class_name: "Category"
  belongs_to :child, class_name: "Category"
end

粘纸:

class StickerSerializer < ActiveModel::Serializer
  embed :ids, include: true
  attributes :id, :text, :audio, :created_at, :image, :smallImage, :updated_at, :stickerServerID
    has_many :categories
end

分类

class CategorySerializer < ActiveModel::Serializer
  embed :ids, include: true
  attributes :id, :name, :catImage, :created_at, :catOrder, :catServerID, :updated_at
  has_many :stickers
  has_many :children
  has_many :parents
end

以下是Ember Models:

粘纸:

App.Sticker = DS.Model.extend({
    audio: DS.attr("string"),
    image: DS.attr("string"),
    smallImage: DS.attr("string"),
    stickerServerID: DS.attr("string"),
    text: DS.attr("string"),
    updated_at: DS.attr("date"),
    created_at: DS.attr("date"),

    categories: DS.hasMany("category")
});

分类

App.Category = DS.Model.extend({
    name: DS.attr("string"),
    catImage: DS.attr("string"),
    catOrder: DS.attr("string"),
    catServerID: DS.attr("string"),
    updated_at: DS.attr("date"),
    created_at: DS.attr("date"),

    stickers: DS.hasMany("sticker"),

    children: DS.hasMany("category",{inverse:'parents'}),
    parents: DS.hasMany("category",{inverse:'children'})
});

商品

App.ApplicationSerializer = DS.ActiveModelSerializer.extend({
  keyForAttribute: function(attr){
    console.log("keyForAttribute:"+attr+"->"+this._super(attr));
  if (attr == "smallImage" || attr == "stickerServerID" || attr == "catOrder" || attr == "catImage" || attr == "catServerID"){
    console.log("try:"+attr);
    return attr;
  }else{
    return this._super(attr);
  }
});

App.ApplicationStore = DS.Store.extend({
  adapter: '-active-model'
});

Chrome报告的错误:

  

加载路线时出错:错误:未找到&#39; child&#39;

的模型

Firefox报告的错误无用: - /

很高兴添加任何其他有用的信息!提前谢谢!

1 个答案:

答案 0 :(得分:1)

有一种方法可以做到这一点,但它并不完美。

  • child_ids添加到序列化程序中的attributes
  • 在Ember中将children设置为模型中的DS.hasMany

滑轨:

# app/serializers/category_serializer.rb    
class CategorySerializer < ActiveModel::Serializer
  embed :ids, :include => true
  attributes :id, :name, :child_ids
end
Ember(EmberCLI):

// app/models/category.js
import DS from 'ember-data';

export default DS.Model.extend({
  children: DS.hasMany('category'),
  name: DS.attr('string'),
});

问题是序列化程序无法自动加载子项,因此您需要始终一次加载所有类别。