簡體   English   中英

如何在 Rails API 中使用 FK 檢索模型的實例?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM