如何解决将嵌套的关联呈现为json
下面是我的模型定义
# GoogleApp model
class GoogleApp < ApplicationRecord
has_many :gmail_users,foreign_key: 'app_account',primary_key: 'google_account',dependent: :destroy
has_many :gmail_threads,dependent: :destroy
end
# GmailUser model
class GmailUser < ApplicationRecord
belongs_to :google_app,optional: true
has_one :gmail_thread,foreign_key: 'user_id',primary_key: 'user_id',dependent: :destroy
end
# GmailThread model
class GmailThread < ApplicationRecord
belongs_to :google_app,optional: true
belongs_to :gmail_user,optional: true
has_many :gmail_messages,-> { order "sent_at asc" },foreign_key: 'thread_id',primary_key: 'thread_id',dependent: :destroy
end
# GmailMessage model
class GmailMessage < ApplicationRecord
belongs_to :gmail_thread,optional: true
has_many :gmail_attachments,foreign_key: 'message_id',primary_key: 'message_id',dependent: :destroy
end
# GmailAttachment model
require "base64"
class GmailAttachment < ApplicationRecord
belongs_to :gmail_message,optional: true
def encode_as_base64_data
Base64.encode64(self.base64_data)
end
end
我正在尝试返回具有以下嵌套关联的GoogleApp实例
render status: 200,json: @google_app.to_json({include: [gmail_users: {include: [gmail_thread: {include: [gmail_messages: {include: {gmail_attachments: (except: :base64_data,methods: [:encode_as_base64_data])}}]}]}]})
但这会在except
上给出语法错误,即
SyntaxError(/home/work/projects/backend/app/controllers/gmail_controller.rb:40:语法错误,意外的tLABEL ... e:{gmail_attachments:(除了::base64_data,方法:[:enc ... ... ^ ~~~~~~ ):
我无法解决此语法错误问题。当我这样做的时候
render status: 200,json: GmailAttachment.first.to_json(except: [:base64_data],methods: [:encode_as_base64_data])
然后按预期工作。
解决方法
exclude
应该换成{}
而不是()
render status: 200,json: @google_app.to_json({include: [gmail_users: {include: [gmail_thread: {include: [gmail_messages: {include: {gmail_attachments: {except: :base64_data,methods: [:encode_as_base64_data]}}]}]}]})
我建议使用jbuilder Gem以可维护的方式包括嵌套模型。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。