【问题标题】:jsonapi::Serializer Specify Foreign Key in Association belongs_to / has_manyjsonapi::Serializer 在 Association belongs_to / has_many 中指定外键
【发布时间】:2021-06-30 15:54:45
【问题描述】:

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

这会导致表有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) 时,我收到以下错误,好像序列化程序正在尝试查找与 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

【问题讨论】:

    标签: ruby-on-rails ruby active-model-serializers fastjsonapi


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      相关资源
      最近更新 更多