2013-08-30 61 views
0

我有以下的控制器動作返回當前用戶收件箱消息(我使用mailboxer):追加到現有/空白陣列

def index 
    @conversations = mailbox.inbox 
    render :template => "/api/communications/index.json.jbuilder" 
    end 

這使得一個JSON響應,其中在jbuilder踢:

json.array!(@conversations) do |conversation| 
    json.id conversation.id 
    json.sender conversation.last_sender.name 
    json.subject conversation.subject 
    json.body conversation.last_message.body 
    json.current_user_id current_user.id 
    json.current_user_name current_user.name 
    json.admin current_user.is_admin? 
end 

請注意最後3個由current_user構建的json值,這是在我的application_controller中聲明的幫助器方法。我在這裏有兩個問題:

1)雖然這種工作,但最好將current_user值從數組中分離出來。如果我只是將它們移動出塊,我得到了以下錯誤:

TypeError (can't convert String into Integer)

2)如果CURRENT_USER在他們的收件箱沒有對話的數組將爲空(@conversations爲空),因此CURRENT_USER值就不傳遞。

所以回顧一下:我可以將current_user值附加到現有數組,並且可以將current_user值附加到空數組嗎?

回答

0

嵌入另一根

json.user do |user| 
    json.current_user_id current_user.id 
    json.current_user_name current_user.name 
    json.admin current_user.is_admin? 

    json.conversations do |json| 
     json.array!(@conversations) do |conversation| 
     json.id conversation.id 
     json.sender conversation.last_sender.name 
     json.subject conversation.subject 
     json.body conversation.last_message.body 
     end 
    end 
end