Sequel JsonSerializer 与别名冲突

发布于 2024-11-07 00:19:50 字数 826 浏览 4 评论 0原文

在 Sinatra Web 应用程序中,我尝试从数据库获取数据并将其转换为 UI 可接受的对象(最后转换为 JSON)。但 UI 字段和 DB 字段所需的属性名称存在一些差异。所以我使用了带有别名的 Sequel 查询:

Sequel::Model.plugin :json_serializer

class Alarm < Sequel::Model
#       attr_accessor :id, :Alarm
end
filter = Alarm.filter(:NEName => params[:name]).select(:AlarmNo___id, :AlarmMsg___Alarm).all

但是当我尝试进行此转换时:

res = filter.to_json

我得到: **undefined method** 'id' for # Alarm:0x000000027403e0


我还尝试将访问器添加到模型(参见注释掉的行) attr_accessor:id,:警报 并得到很多像这样的对象: {"json_class":"Alarm","id":null,"Alarm":null} ,这似乎是合乎逻辑的结果。


那么,Q1:如何使后续别名与 json_serializer 插件一起使用?

Q2:可能还有一些其他解决方案来提供此映射(无需创建新类和/或添加其他转换方法) - 例如通过 to_json 方法中的选项影响 json 属性名称等

In a Sinatra web application I am trying to get data from DB and convert them into object that is acceptable for UI (and finally to JSON). But there is some difference in names of attributes needed for UI and DB fields. So I have used Sequel query with aliasing:

Sequel::Model.plugin :json_serializer

class Alarm < Sequel::Model
#       attr_accessor :id, :Alarm
end
filter = Alarm.filter(:NEName => params[:name]).select(:AlarmNo___id, :AlarmMsg___Alarm).all

But when I am trying to do this conversion:

res = filter.to_json

I get: **undefined method** 'id' for # Alarm:0x000000027403e0


I also tried to add accessors to the model (see commented out line)
attr_accessor :id, :Alarm
and got a lot of objects like this: {"json_class":"Alarm","id":null,"Alarm":null}, which seems to be logical result.


So, Q1: how to make sequel aliasing work with json_serializer plugin?

Q2: Probably, there might be some other solutions to provide this mapping (without creation of new classes and/or adding additional conversion methods) - like influencing on json attributes name through options in to_json method, etc

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆之渊 2024-11-14 00:19:50

您应该像这样定义 id 和 Alarm 方法实例方法:

class Alarm < Sequel::Model
  def id() self[:id] end
  def Alarm() self[:Alarm] end
end

attr_accessor 不起作用,因为它会查找实例变量,而不是 @values 哈希中的条目。 Sequel::Model#[] 在 @values 哈希中查找同名条目。

You should define id and Alarm methods instance methods like this:

class Alarm < Sequel::Model
  def id() self[:id] end
  def Alarm() self[:Alarm] end
end

attr_accessor doesn't work because that looks for instance variables, not for entries in the @values hash. Sequel::Model#[] looks in the @values hash for the entry with the same name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文