mercredi 20 décembre 2017

Create a polymorphic record in ember front and rails back

I'm having some troubles creating a polymorphic record with emberjs for a rails backend. My little project is about cars. Please need some help.

This is my rails backend. All of their controllers were generated by scaffolds. So, they're the same.

class Vehicle < ApplicationRecord
  belongs_to :concess
  has_many :comments, as: :commented
end

class Concess < ApplicationRecord
  has_many :vehicles, dependent: :destroy
  has_many :comments, as: :commented
end

class Comment < ApplicationRecord
  belongs_to :commented, polymorphic: true
end

And these are my emberjs models and the main issue (comment controller)

vehicle model:

import DS from 'ember-data';
import Commented from './commented'

export default Commented.extend({
  model: DS.attr('string'),
  concess: DS.belongsTo('concess')
});

concess model:

import DS from 'ember-data';
import Commented from './commented'

export default Commented.extend({
  name: DS.attr('string'),
  createdAt: DS.attr('date'),
  vehicles: DS.hasMany('vehicle')
});

comment model:

import DS from 'ember-data';

export default DS.Model.extend({
  body: DS.attr('string'),
  commented: DS.belongsTo('commented', {polymorphic: true}),
  concess: DS.belongsTo('concess'),
  vehicle: DS.belongsTo('vehicle')
});

commented model:

import DS from 'ember-data';

export default DS.Model.extend({
  comments: DS.hasMany('comment')
});

Finally the comment controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    createComment: function(params){
      let body = this.get('body');
      let concess = this.get('store').findRecord('concess', params.id)
      var comment = this.store.createRecord('comment',{
        body: body,
        commented: concess
      });
      comment.save();
      this.transitionToRoute('concesses.show', params.id);

    }
  }
});




Aucun commentaire:

Enregistrer un commentaire