Question

I have the following controller action which returns current users inbox messages (I'm using mailboxer):

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

This renders a json response where jbuilder kicks in:

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

Note the last 3 json values that are built off current_user which is a helper method declared in my application_controller. I have two questions here:

1) Alhthough this kind of works, it would be better to break the current_user values out of the array. If I simply move them out of the block I get the following error:

TypeError (can't convert String into Integer)

2) If the current_user has no conversations in their inbox the array will be empty (@conversations is blank) so current_user values are not passed.

So to recap: Can I append current_user values to an existing array and can I append current_user values to an empty array?

Was it helpful?

Solution

embedded another root

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top