如何使db结构适应预期的API(How to adapt db structure to the expected API)

编程入门 行业动态 更新时间:2024-10-22 11:13:34
如何使db结构适应预期的API(How to adapt db structure to the expected API)

假设我有一个客户端应用程序,它希望显示以下JSON结构。

{'foo': {'bar': '1'}}

我想将相关的db结构保持为:

create_table :foos do |t| t.string :baar end

所以我想使用baar而不是bar作为db列的名称。 你怎么看待这些东西的别名如下:

alias_attribute :bar, :baar

Let's say I have client side app which expects the following JSON structure as show.

{'foo': {'bar': '1'}}

I'd like to keep related db structure as:

create_table :foos do |t| t.string :baar end

so I'd like to use baar instead of bar as name of db column. What do you think about just aliasing this stuff to something like:

alias_attribute :bar, :baar

最满意答案

渲染的json结构与您使用的数据库结构无关。 attribute_names可以在json render函数中设置(并且可以与底层数据库字段名相同或不同)

从表结构继续你有:

create_table :foos do |t| t.string :baar end

这将对应于foo模型:

class Foo < ActiveRecord::Base .. end

foos_controller.rb的json渲染函数 - 对于show动作(例如) - 将如下所示:

class FoosController < < ApplicationController def show @foo = Foo.find(1) respond_to do |format| format.json { render json: { foo: { baar: @foo.bar } } } end end end

这里,json属性 - baar可以是任何东西,并且它被链接到foos表中的bar字段。

The rendered json structure is not tied to the database structure you use. The attribute_names can be set in the json render function (and can be same or different from the underlying database field name)

Continuing from the table structure you have:

create_table :foos do |t| t.string :baar end

This would correspond to the foo model:

class Foo < ActiveRecord::Base .. end

The json render function within foos_controller.rb - for the show action (for example)- would be as follows:

class FoosController < < ApplicationController def show @foo = Foo.find(1) respond_to do |format| format.json { render json: { foo: { baar: @foo.bar } } } end end end

Here, the json attribute - baar could be anything, and that is being linked to the bar field in the foos table.

更多推荐

本文发布于:2023-08-04 08:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1412567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   API   db   expected   structure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!