【发布时间】: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