简体   繁体   中英

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. 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.

What I generally do in Rails if I want to retrieve the title of a Job Opening via its Requirement is as follow:

requirement.opening.title

This has always worked fine for me in Rails.

However, I am not sure how I can do the same with 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 ):

[
    {
        "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 ):

    [{
        "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)? Ideally, I could do something like:

requirement.opening_id.title

However , in the Requirement API, there is not attribute 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

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"
},
...
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM