简体   繁体   中英

ember-data dynamic number of DS.attr 's

So i have a ember-data model and i want my users to be able to create different / more DS.attr per item and call them whatever they like. This will then send the json to rails server where i am using mondodb. I can then check to see if key is defined and if not create it for this document and save it in mongo.

The problem is you have to hardcode all the DS.attr 's when extending the DS.Model but i dont know them all at that point.

Is there a way to reopen the DS.Model and somehow loop over the json keys passed ( or i could pass all keys in a allKeys field to the client from rails ???).

Then when someone wants to create a different attribute i can dynamically reopen the model and add this DS.attr ?

Anyone any ideas how to do this or if its even possible ??

Any help, examples or idea would me great!

thanks a lot Rick

Assuming that you have a App.Post model and you want your users to store additional attributes for posts. First create a model App.MyModelTypes and store all your modelTypes in it:

App.MyModelTypes = DS.Model.extend({
  modelType: DS.attr('string') // e.g. App.Post, App.Comment
  attributes: DS.hasMany('App.Attribute')
});

Then your App.Post should like:

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  body: DS.attr('string'),
  // ... other base attributes
});

Define a model App.Attribute as follows:

App.Attribute = DS.Model.extend({
  name: DS.attr('string')
  attrType: DS.attr('string'),

  theModelType: DS.belongsTo('App.Model'),
  attributeValues: DS.hasMany('App.AttributeValue')
});

When a user creates a new attribute for post, the app should create a new App.Attribute that belongs to App.MyModelType App.Post .

Finally you need a model for storing the custom attributes values for Posts:

App.AttributeValue = DS.Model.extend({
  theModelType: DS.belongsTo('App.MyModelTypes'),
  targetId: DS.attr('number'),
  attribute: DS.belongsTo('App.Attribute'),
  value: DS.attr('string') // attribute.attrType will give us the type 
});

When a user edits the attribute value of a certain post, you store the post.id in targetId , in theModelType you store App.Post , etc.

Let me know if that works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM