2017-10-06 64 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'對象中刪除用戶 –