[英]Blueprinter not returning model defined methods
使用 blueprinter gem 仅返回列定义的属性。 任何返回实例方法或重命名关联的尝试都不起作用。
蓝图中定义的字段/关联不会在 JSON 以及 class 中定义的任何方法中返回。
例如。
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
被定义为 model 上的实例方法。 这些不会被退回。 此外,蓝图中定义的关联也不会被返回。
我通过辅助方法调用蓝图,但我认为这不应该是一个问题。 直到今天我才遇到这个问题,似乎无法找出原因。
# 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
在获得我在那里提出的问题的意见后,它与条件渲染有关。 如果查询没有返回 object,我最初会收到未定义的方法错误。 所以我使用了全局条件渲染。 这是 repo 中问题的修复。 config.unless = ->(field_name, obj, _options) { obj.public_send(field_name).nil? }
它没有返回定义的实例方法,因为实例方法不响应 object 上的括号表示法。 因此,使用上面的代码片段,而不是他们文档中的代码片段解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.