我正在尝试使用Rails5中的jsonapi-resources 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_type字段来表示与inspectors和buyers的多态关联。这一切在我们当前的Rails设置中都能正常工作,但是当我尝试使用jsonapi-resources为JSON:API设置它时,我遇到了错误。
现在是对应的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?
在此之前,感谢您帮助我完成此设置!
发布于 2020-11-07 00:14:38
核心问题实际上与jsonapi-resources无关,而是关联。belongs_to资源的反面总是指向另一个表上的外键的has_one或has_many (反之亦然)。
class User < ApplicationRecord
belongs_to :profile, polymorphic: true
end
class Inspector < ApplicationRecord
has_one :user, as: :profile
end
class Buyer < ApplicationRecord
has_one :user, as: :profile
end拥有两个相互指向的belongs_to关联将意味着两端都有外键-这是糟糕的DB设计,因为重复(应该只有一个真值来源),并且在ActiveRecord中不会真正工作,因为当您关联两个模型时,它只会在一侧写入外键。
https://stackoverflow.com/questions/64717137
复制相似问题