1

我有一个无法修改的数据库,因为它是从我无法控制的节点中填充的只读数据库。

这会导致表格foreign_keys与 Rails 默认方式不同。您可以在以下模型中看到当前情况:

# 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配置查询控制器(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

4

1 回答 1

1

您应该使用以下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

于 2021-04-26T14:10:19.320 回答