Batman.js: Related model undefined for polymorphic

2019-06-13 16:21发布

问题:

I'm running into an issue trying to implement polymorphic associations on a Batman model. I'm getting this error in the console:

Related model undefined for polymorphic association not found.

I'm having a hard time tracking down where I am going wrong. Where should I look to find the missing piece?

My models look something like this:

class Admin.Product.PopularCollectables extends Batman.Model
  @belongsTo 'collectable', polymorphic: true

class Admin.Item extends Batman.Model
  @hasOne 'popular_collectable', as: 'collectable'

回答1:

When Batman loads a related model in an association, it checks a namespace. By default, the namespace is Batman.currentApp (which is your app after you call MyApp.run()), but you can also pass a namespace when you declare the association:

class Admin.Item extends Batman.Model
  @hasOne 'popular_collectable', as: 'collectable', namespace: Admin.Product

That way, Batman will look for PopularCollectable on Admin.Product instead of on Admin.



回答2:

I was able to workaround this issue by embedding the belongs_to side of a has_many relation inside the parent Batman Model instance when it is sent to the client from Rails:

format.json {render :json => @post, :include => {:comments => {:include => :comments}}}