【发布时间】:2017-06-06 05:37:30
【问题描述】:
我目前正在开发一个小型 Rails 5 应用程序,我需要根据某些事件将 ActiveRecord 对象传递给外部服务。在我的模型中,我定义了以下内容:
# /models/user.rb
after_create :notify_external_service_of_user_creation
def notify_external_service_of_user_creation
EventHandler.new(
event_kind: :create_user,
content: self
)
end
EventHandler 然后将此对象转换为 JSON,并通过 HTTP 请求将其发送到外部服务。通过在对象上调用 .to_json 会呈现一个 JSON 输出,如下所示:
{
"id":1234,
"email":"test@testemail.dk",
"first_name":"Thomas",
"last_name":"Anderson",
"association_id":12,
"another_association_id":356
}
现在,我需要一种将所有第一级关联直接包含在其中的方法,而不仅仅是显示foreign_key。所以我正在寻找的结构是这样的:
{
"id":1234,
"email":"test@testemail.dk",
"first_name":"Thomas",
"last_name":"Anderson",
"association_id":{
"attr1":"some_data",
"attr2":"another_value"
},
"another_association_id":{
"attr1":"some_data",
"attr2":"another_value"
},
}
我的第一个想法是像这样反映模型:object.class.name.constantize.reflect_on_all_associations.map(&:name),其中object 是本例中的用户实例,并使用此列表循环关联并将它们包含在输出中。不过这似乎相当乏味,所以我想知道是否有更好的方法可以使用 Ruby 2.4 和 Rails 5 来实现这一点。
【问题讨论】:
-
JSON序列化用什么? github.com/rails-api/active_model_serializers 支持关联。
-
@MikDiet 我在对象上打电话给
.to_json,仅此而已。
标签: ruby-on-rails json ruby ruby-on-rails-5 ruby-2.4