[英]jsonapi::Serializer Specify Foreign Key in Association belongs_to / has_many
I have a database that I cannot modify as it is a read-only populated from a node I don't control.我有一个无法修改的数据库,因为它是从我无法控制的节点中填充的只读数据库。
This causes the tables to have foreign_keys
that are different from the Rails default way.这会导致表具有不同于 Rails 默认方式的foreign_keys
。 You can see the current situation in the models below:您可以在以下模型中看到当前情况:
# 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
rather thanstake_address_id
addr_id
而不是stake_address_id
Now I am creating a controller to fetch one of the model, using a serializer to show the associated model.现在我正在创建一个 controller 来获取 model 之一,使用序列化器显示关联的 model。
class EpochStakeController < ApplicationController
def index
epoch_stakes = EpochStake.all
render json: EpochStakeSerializer.new(epoch_stakes)
end
end
It seems though that when I try to tell the JSONAPI::Serializer
to be aware of the different foreign_key
, that doesn't get taken into account:似乎当我尝试告诉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
Infact when I query the controller ( /epoch_stakes
) with the configuration above I receive the following error, as if the serializer is trying to look for the association with the Rails default foreign_key
rather than the one I specified in the serializer:事实上,当我使用上述配置查询 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'
How can I make the serializer aware of the different foreign_key
?如何让序列化程序知道不同的foreign_key
?
You should use the id_method_name
option:您应该使用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
See documentation: https://github.com/jsonapi-serializer/jsonapi-serializer#customizable-options请参阅文档: https://github.com/jsonapi-serializer/jsonapi-serializer#customizable-options
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.