[英]How do I retrieve a instance of the model with a FK in a Rails API?
I am creating a job portal website with Rails API.我正在使用 Rails API 创建一个工作门户网站。 Each Job Opening has one or more of Requirements
每个职位空缺都有一个或多个要求
My Job Opening model is:我的职位空缺模型是:
create_table "openings", force: :cascade do |t|
t.string "title"
t.integer "user_id"
end
My Requirements model is:我的需求模型是:
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
Each Job Opening has one or more requirement.每个职位空缺都有一个或多个要求。 Therefore the FK is on Requirement with connection to Job Opening.
因此,FK 与职位空缺有关。
What I generally do in Rails if I want to retrieve the title of a Job Opening via its Requirement is as follow:如果我想通过其 Requirement 检索职位空缺的标题,我通常在 Rails 中执行的操作如下:
requirement.opening.title
This has always worked fine for me in Rails.这在 Rails 中对我来说一直很好用。
However, I am not sure how I can do the same with Rails API.但是,我不确定如何使用 Rails API 做同样的事情。
I want to retrieve and display all the Job Opening with their relative Requirements.我想检索并显示所有职位空缺及其相关要求。 The Job Opening API returns something like (for the
index action
): 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
},
....
]
The Requirement API returns something like (for the index action
): 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
},
...
]
How can I get all the Job openings titlte and relative requirements in my client (ReactJS)?如何在我的客户(ReactJS)中获得所有职位空缺和相关要求? Ideally, I could do something like:
理想情况下,我可以执行以下操作:
requirement.opening_id.title
However , in the Requirement API, there is not attribute title.但是,在 Requirement API 中,没有属性 title。 What I am missing?
我缺少什么?
The job opening api converts the record into a hash using the #as_json
method, so in your Requirement
model you can modify the returned hash to include additional attributes职位空缺 api 使用
#as_json
方法将记录转换为散列,因此在您的Requirement
模型中,您可以修改返回的散列以包含其他属性
def as_json(*)
super.tap do |hash|
hash['opening_title'] = opening.title
end
end
Which should then give you然后应该给你
[{
"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.