1

jsonapi-resourcesRails 5 で gemを使用してポリモーフィックな関連付けをセットアップしようとしています。

と呼ばれるポリモーフィックな関連付けを持つUserモデルがprofileありInspectorますBuyer。切り捨てられたモデルは次のとおりです。

class User < ApplicationRecord
  belongs_to :profile, polymorphic: true
end

class Inspector < ApplicationRecord
  belongs_to :user
end

class Buyer < ApplicationRecord
  belongs_to :user
end

usersテーブルには、 および への多態的な関連付けを表す対応するおよびprofile_idフィールドprofile_typeinspectorsありbuyersます。これはすべて、現在の Rails セットアップで期待どおりに機能しますが、JSON:API を使用してこれをセットアップしようとすると、エラーが発生しますjsonapi-resources

そして今、対応するjsonapi-resourcesリソースとコントローラー (指示に従って):

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

私が知る限り、すべてが適切にセットアップされているはずですが、エンドポイントに到達すると次のエラーが発生します。

"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'",

スタック トレースに記載されている内容を掘り下げるrelationship.rbと、ポリモーフィック型を解決できないように見えるため、次のことを試しました。

class Api::V1::Mobile::UserResource < JSONAPI::Resource
  immutable
  attributes :name, :email
  has_one :profile, polymorphic: true, polymorphic_types: ['inspector', 'buyer']
end

しかし、悲しいかな、別のエラー:Can't join 'User' to association named 'inspector'; perhaps you misspelled it?

このセットアップを取得するための助けを前もって感謝します!

4

1 に答える 1