Sequel JsonSerializer 与别名冲突
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该像这样定义 id 和 Alarm 方法实例方法:
attr_accessor
不起作用,因为它会查找实例变量,而不是 @values 哈希中的条目。Sequel::Model#[]
在 @values 哈希中查找同名条目。You should define id and Alarm methods instance methods like this:
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.