【问题标题】:Blueprinter not returning model defined methods蓝图不返回模型定义的方法
【发布时间】:2020-11-10 02:42:33
【问题描述】:

使用 blueprinter gem 只会返回列定义的属性。任何返回实例方法或重命名关联的尝试都不起作用。

在 JSON 中没有返回蓝图中定义的字段/关联,以及在类中定义的任何方法。

例如

class UserBlueprint < BlueprinterBase
  identifier :slug, name: :id

  fields :first_name, :last_name, :full_name, :formatted_dob

  association :locations, name: :location, blueprint: LocationBlueprint do |user, _options|
    user.locations.first
  end
end

架构中定义的字段是:slug, :first_name, :last_name,并且可以正常返回。但是:formatted_dob:full_name 被定义为模型上的实例方法。这些不会被退回。此外,蓝图中定义的关联也没有返回。

我通过辅助方法调用蓝图,但我认为这不是问题。直到今天我才遇到这个问题,似乎无法找出原因。

# helper method definition
def serialized_resource(resource, blueprint, options = {})
  JSON.parse(blueprint.render(resource, options))
end

# called in the controller with...
render json: { users: serialized_resource(User.all, UserBlueprint) }

而回报是:

"users": [
  {
    "id": "45hsadfknadsf98hasn",
    "first_name": "FirstName",
    "last_name": "LastName"
  },
  ...
]

感谢您的任何帮助/建议:D

【问题讨论】:

    标签: ruby-on-rails serialization


    【解决方案1】:

    在获得我在那里提出的问题的意见后,它与条件渲染有关。如果查询没有返回对象,我最初会收到未定义的方法错误。所以我使用了全局条件渲染。这是 repo 中问题的修复。 config.unless = -&gt;(field_name, obj, _options) { obj.public_send(field_name).nil? }

    它没有返回定义的实例方法,因为实例方法不响应对象上的括号表示法。所以使用上面的代码 sn-p,而不是他们文档中的代码解决了这个问题。

    Blueprinter Repo Issue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      相关资源
      最近更新 更多