2017-10-06 62 views
1

聚集的回报格式化我从续集就是这个样子的东西返回的查询:优化从续集

posts = [ 
    <Post: @attributes={ id: 1, title: 'Foo', text: 'Bar', user_id: 21, user: <User: @attributes={ id: 21, name: 'John'}>}>, 
    <Post: @attributes={ id: 2, title: 'Bar', text: 'Foo', user_id: 21, user: <User: @attributes={ id: 21, name: 'John'}>}>, 
    <Post: @attributes={ id: 3, title: 'FooBar', text: 'FooBar', user_id: 19, user: <User: @attributes={ id: 19, name: 'Jane'}>}> 
] 

PostUser对象的数组。

我想这样寄回给用户:

json = { 
    posts:[ 
    { id: 1, title: 'Foo', text: 'Bar', user_id: 21 }, 
    { id: 2, title: 'Bar', text: 'Foo', user_id: 21 }, 
    { id: 3, title: 'FooBar', text: 'FooBar', user_id: 19 } 
    ], 
    users: [ 
    { id: 21, name: 'John'}, 
    { id: 19, name: 'Jane'} 
    ] 
} 

什么是最有效的方式来提取原始数组这个哈希? 这是我使用它现在的代码:

def prepare_json(array) 
    posts = [] 
    users = Hash[] 
    array.each do |item| 
    posts.push(item.post) 

    # user id is unique so I use it to avoid duplication on 
    # the users array 
    users[item.user.id.to_sym] = item.user 
    end 
    { posts: posts, users: users.values } 
end 

回答

2
users = posts.map{|h| h.delete(:user)}.uniq 
json = {posts: posts, users: users} 

结果:

{ 
    :posts=>[{:id=>1, :title=>"Foo", :text=>"Bar", :user_id=>21}, {:id=>2, :title=>"Bar", :text=>"Foo", :user_id=>21}, {:id=>3, :title=>"FooBar", :text=>"FooBar", :user_id=>19}], 
    :users=>[{:id=>21, :name=>"John"}, {:id=>19, :name=>"Jane"}] 
} 
+0

对不起,我应该作出更清楚,通过续集返回的数组不是由组成散列,但通过Post和User对象。如果您使用'uniq(&:id)',您的答案在这种情况下仍然有效。 我还需要在返回之前从'Post'对象中删除用户 –