[英]How do I retrieve a instance of the model with a FK in a Rails API?
我正在使用 Rails API 创建一个工作门户网站。 每个职位空缺都有一个或多个要求
我的职位空缺模型是:
create_table "openings", force: :cascade do |t|
t.string "title"
t.integer "user_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 与职位空缺有关。
如果我想通过其 Requirement 检索职位空缺的标题,我通常在 Rails 中执行的操作如下:
requirement.opening.title
这在 Rails 中对我来说一直很好用。
但是,我不确定如何使用 Rails API 做同样的事情。
我想检索并显示所有职位空缺及其相关要求。 Job Opening API返回如下内容(对于index action
):
[
{
"id": 5,
"title": "Try1",
"created_at": "2019-12-30T01:29:32.779Z",
"updated_at": "2019-12-30T01:29:32.779Z",
"user_id": 1
},
....
]
Requirement API返回类似(对于index action
):
[{
"id": 1,
"requirements": ["Java", "Python"],
"created_at": "2019-12-30T01:36:48.786Z",
"updated_at": "2019-12-30T01:36:48.786Z",
"opening_id": 5
},
...
]
如何在我的客户(ReactJS)中获得所有职位空缺和相关要求? 理想情况下,我可以执行以下操作:
requirement.opening_id.title
但是,在 Requirement API 中,没有属性 title。 我缺少什么?
职位空缺 api 使用#as_json
方法将记录转换为散列,因此在您的Requirement
模型中,您可以修改返回的散列以包含其他属性
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"
},
...
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.