0

A rails object has following style of info. Say for example, if I do res.students[0].student_id it prints 1

The rails object is the response from other service and it is a proto.

"Students": [
    {
      "student_id": "1",
      "marks": 66,
      "address": 1,234 street,
      "name" : "",
    },
    {
      "student_id": "2",
      "marks": 97,
      "address": 4, 567 street,
      "name" : "",
    },
]

//Name will be empty in this structure

  1. But, How can I get all student_id to an array in Ruby on Rails?
  2. Also, how can I pass an array of student IDs to SQL query and get array of names?
7
  • Oh, so is that not an hash? Commented Jun 5, 2020 at 18:21
  • @Ursus Its not an hash. Commented Jun 5, 2020 at 18:21
  • then what data type is it? Commented Jun 5, 2020 at 18:25
  • @lacostenycoder - updated. Commented Jun 5, 2020 at 18:27
  • can you be more specific about part 2 of your question? Commented Jun 5, 2020 at 18:28

1 Answer 1

3

We can assueme res.students is an Enumerable so why not just .map?

student_ids = res.students.map{|r| r.student_id}

For sql perhaps you're looking for this?

Student.where(id: student_ids ).pluck(:name)
Sign up to request clarification or add additional context in comments.

4 Comments

pluck also works on Enumerable objects if the objects within respond to []. So res.students.pluck(:student_id) would return a list of student ids.
@lacostenycoder - I have a follow up question. After getting names with sql queries I will be assigning it to each student element. If I use an array and say for 3rd element there is no name returned the array would look like ["Mark" , "Tom", "", "Dick", "harry"] and when I assign it back , I have to exactly map it to corresponding studentId. Is map the only way? Ruby seems to have lots of shortcut one-line magic. Is there anything of that sort for this ?
@3limin4t0r I guess that was added in newer versions of Rails, do you know when?
@sofs1 I'm not sure I understand exactly what you want to do in your comment above. Please post a new question if you need more help on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.