2013-08-30 63 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