Ruby on rails 如何在Rails API中检索带有FK的模型实例?
我正在用Rails API创建一个工作门户网站。每个职位空缺都有一个或多个要求 我的求职模式是:Ruby on rails 如何在Rails API中检索带有FK的模型实例?,ruby-on-rails,Ruby On Rails,我正在用Rails API创建一个工作门户网站。每个职位空缺都有一个或多个要求 我的求职模式是: create_table "requirements", force: :cascade do |t| t.string "requirements" t.bigint "opening_id", null: false t.index ["opening_id"], name: "index_requirements_on_opening_id" end 我的需求
create_table "requirements", force: :cascade do |t|
t.string "requirements"
t.bigint "opening_id", null: false
t.index ["opening_id"], name: "index_requirements_on_opening_id"
end
我的需求模型是:
create_table "requirements", force: :cascade do |t|
t.string "requirements"
t.bigint "opening_id", null: false
t.index ["opening_id"], name: "index_requirements_on_opening_id"
end
每个职位空缺都有一个或多个要求。
因此,FK符合与职位空缺相关的要求
如果我想通过职位空缺的要求检索职位空缺的标题,我通常在Rails中执行的操作如下:
requirement.opening.title
在Rails中,这对我来说一直都很好
但是,我不确定如何使用Rails API实现同样的功能
我想检索并显示所有空缺职位及其相关要求。
作业打开API为索引操作返回如下内容:
需求API为索引操作返回类似的内容:
如何在我的客户中获得所有职位空缺标题和相关要求?
理想情况下,我可以这样做:
requirement.opening_id.title
但是,在需求API中,没有属性标题。
我缺少什么?作业打开api使用as_json方法将记录转换为哈希,因此在您的需求模型中,您可以修改返回的哈希以包含其他属性
def as_json(*)
super.tap do |hash|
hash['opening_title'] = opening.title
end
end
那应该给你什么
[{
"id": 1,
"requirements": ["Java", "Python"],
"created_at": "2019-12-30T01:36:48.786Z",
"updated_at": "2019-12-30T01:36:48.786Z",
"opening_id": 5,
"opening_title": "Programmer for Acme Corporation"
},
...
]
def as_json(*)
super.tap do |hash|
hash['opening_title'] = opening.title
end
end
[{
"id": 1,
"requirements": ["Java", "Python"],
"created_at": "2019-12-30T01:36:48.786Z",
"updated_at": "2019-12-30T01:36:48.786Z",
"opening_id": 5,
"opening_title": "Programmer for Acme Corporation"
},
...
]