jsonapi::Serializer 在关联中指定外键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

现在我正在创建一个控制器来获取模型之一,使用序列化程序来显示关联的模型。

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

事实上,当我使用上述配置查询控制器 (/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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)