1

Ive got a table which consists of two fields called follower_id and followed_id. I need to create a query which creates an array of from each row and puts that in an overall array so that the end structure looks like:

"edges": [
    ["1", "2"],
    ["1", "3"],
    ["3", "4"],
    ["3", "5"]
  ]

so far I have

 def self.including_relationships
  result={}
  result["edges"] Relationship.all.each do |relationship|
    result[""]= Relationship.select(:follower_id.to_s,:follower_id.to_s)
  #the code here is called once for each user
  # user is accessible by 'user' variable
end
  result
end

but this produces:

 edges: [
"[4, 3, 3, 4]",
"[3, 4, 3, 4]"
]
1
  • This seems like a join table. You're not supposed to query those directly. Have you looked at HABTM or has_many :through constructs? See the rails guide for associations. Commented Jul 8, 2015 at 22:26

2 Answers 2

2

You can use map to build an array like:

Relationship.all.map { |r| [r.follower_id.to_s, r.followed_id.to_s] } 
Sign up to request clarification or add additional context in comments.

2 Comments

should be r.followed_id.to_s but otherwise worked. Cheers
In case, you see something missing in any answer, you can edit it. However, I fixed it to r.
1

Try this

relationships = Relationship.all.map { |r| [r.follower_id.to_s, followed_id.to_s] }

results = {"edges": relationships }

1 Comment

I get syntax errors- unexpected : and } (although seems balanced?)

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.