从rails

时间:2015-07-08 22:19:29

标签: ruby-on-rails ruby

我有一个表,其中包含两个名为follower_id和followed_id的字段。我需要创建一个查询,从每行创建一个数组并将其放在一个整体数组中,以便结束结构如下所示:

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

到目前为止我已经

 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

但这会产生:

 edges: [
"[4, 3, 3, 4]",
"[3, 4, 3, 4]"
]

2 个答案:

答案 0 :(得分:2)

您可以使用map构建如下数组:

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

答案 1 :(得分:1)

试试这个

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

results = {"edges": relationships }