I'm trying to setup a polymorphic association using the jsonapi-resources
gem in Rails 5.
I have a User
model that has a polymorphic association called profile
, which can be of type Inspector
or Buyer
. Here are the truncated models:
class User < ApplicationRecord
belongs_to :profile, polymorphic: true
end
class Inspector < ApplicationRecord
belongs_to :user
end
class Buyer < ApplicationRecord
belongs_to :user
end
In the users
table, there are corresponding profile_id
and profile_type
fields to represent the polymorphic association to inspectors
and buyers
. This all works as expected in our current Rails setup but I'm running into errors when trying to set this up for JSON:API using jsonapi-resources
.
And now the corresponding jsonapi-resources
resources and controllers (according to the directions):
class Api::V1::Mobile::UserResource < JSONAPI::Resource
immutable
attributes :name, :email
has_one :profile, polymorphic: true
end
class Api::V1::Mobile::ProfileResource < JSONAPI::Resource
end
class Api::V1::Mobile::ProfilesController < Api::V1::Mobile::BaseController
end
As far as I can tell, everything should now be setup properly but I get the following error when hitting the endpoint:
"exception": "undefined method `collect' for nil:NilClass",
"backtrace": [
".rvm/gems/ruby-2.6.5/gems/jsonapi-resources-0.10.2/lib/jsonapi/relationship.rb:77:in `resource_types'",
When digging into relationship.rb
mentioned in the stack trace it looks like it can't get resolve the polymorphic types, so I tried the following:
class Api::V1::Mobile::UserResource < JSONAPI::Resource
immutable
attributes :name, :email
has_one :profile, polymorphic: true, polymorphic_types: ['inspector', 'buyer']
end
But alas, another error: Can't join 'User' to association named 'inspector'; perhaps you misspelled it?
Thanks in advance for any help with getting this setup!