[英]jsonapi::Serializer Specify Foreign Key in Association belongs_to / has_many
我有一个无法修改的数据库,因为它是从我无法控制的节点中填充的只读数据库。
这会导致表具有不同于 Rails 默认方式的foreign_keys
。 您可以在以下模型中看到当前情况:
# app/models/epoch_stake.rb
class EpochStake < DbSyncRecord
self.table_name = 'epoch_stake'
belongs_to :stake_address, foreign_key: :addr_id
end
# app/models/stake_address.rb
class StakeAddress < DbSyncRecord
self.table_name = "stake_address"
has_many :epoch_stakes, foreign_key: :addr_id
end
addr_id
而不是stake_address_id
现在我正在创建一个 controller 来获取 model 之一,使用序列化器显示关联的 model。
class EpochStakeController < ApplicationController
def index
epoch_stakes = EpochStake.all
render json: EpochStakeSerializer.new(epoch_stakes)
end
end
似乎当我尝试告诉JSONAPI::Serializer
了解不同的foreign_key
时,并没有考虑到这一点:
# app/serializers/epoch_stake_serializers.rb
class EpochStakeSerializer
include JSONAPI::Serializer
attributes :epoch_no, :amount
belongs_to :stake_address, foreign_key: :addr_id
end
事实上,当我使用上述配置查询 controller ( /epoch_stakes
) 时,我收到以下错误,好像序列化程序正在尝试查找与 Rails 默认foreign_key
的关联,而不是我在序列化程序中指定的关联:
NoMethodError: undefined method `stake_address_id' for #<EpochStake:0x00007fcf9f22ad50>
Did you mean? stake_address
stake_address=
from /Users/sergio/.rvm/gems/ruby-2.6.1/gems/activemodel-6.1.3/lib/active_model/attribute_methods.rb:469:in `method_missing'
如何让序列化程序知道不同的foreign_key
?
您应该使用id_method_name
选项:
# app/serializers/epoch_stake_serializers.rb
class EpochStakeSerializer
include JSONAPI::Serializer
attributes :epoch_no, :amount
belongs_to :stake_address, id_method_name: :addr_id
end
请参阅文档: https://github.com/jsonapi-serializer/jsonapi-serializer#customizable-options
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.