Side-loading objects with non-standard class names in EmberJS with Rails+active_model_serializers

前端 未结 3 1573
梦如初夏
梦如初夏 2021-02-09 08:21

I have a few models in Rails that look something like this:

class Issue < ActiveRecord::Base
  belongs_to :reporter, class_name: \'User\'
  belongs_to :assign         


        
相关标签:
3条回答
  • 2021-02-09 08:54

    I had similar problem and have found solution at ActiveModel::Serializers readme. You can use :root option. Try something like this for issue serializer:

    class IssueSerializer < ActiveModel::Serializer
      attributes :id
      embed :ids, include: true
    
      has_one :reporter, :root => "users"
      has_one :assignee, :root => "users"
      has_many :comments
    end
    
    0 讨论(0)
  • 2021-02-09 08:59

    I was having the same issue, adding include: false on the association did the trick for me.

        embed :ids, include: true
        attributes :id, :title
    
        has_many :domains, key: :domains, include: false
        has_many :sessions, key: :sessions
    
    0 讨论(0)
  • 2021-02-09 09:13

    You should read this page. The section of Revision 12 explains about the sideloading of data of the same type:

    Now, homeAddress and workAddress will be expected to be sideloaded together as addresses because they are the same type. Furthermore, the default root naming conventions (underscore and lowercase) will now also be applied to sideloaded root names.

    Your Model should be like:

    App.Issue  = DS.Model.extend({
      reporter: DS.belongsTo('App.User'),
      assignee: DS.belongsTo('App.User'),
      comments: DS.hasMany('App.Comment')
    });
    

    The JSON Result should have a key for the users:

    {
      "issues": [
        {
          "id": 6,
          "reporter_id": 1,
          "assignee_id": 2,
          "comment_ids": [
            3
          ]
        },
      ],
      "comments": [
        {
          "id": 3
          "body": "Great comment"
        }
      ],
      "users": [
        {
          "id": 1
          "name": "Ben Burton"
        },{
          "id": 2
          "name": "Jono Mallanyk"
        }
      ]
    }
    

    Because you configured in your Model that the reporter is of type User, Ember search for a user in the result.

    0 讨论(0)
提交回复
热议问题