1

In my controller I have :

def index
  # Array of Task objects
  @tasks = Task.get_tasks(current_user, params)

  respond_to do |format|
    format.html

    # Sends correct JSON but not including the 'author' object in it
    # format.json { render :json => @tasks.to_json(:include => [:author]) }

    # With this the JSON look correct but is interpreted as a string in the JavaScript code
    format.json { render :json => @tasks.map { |e| e = e.to_json(:include => [:author]) } }
  end
end

Do you know any 'clean' solution to properly pass the :include option when rendering an array converted to JSON ?

EDIT

I am using MongoDB

EDIT (2)

I updated from mongoid (2.0.1) to mongoid (2.0.2) and it works. Sorry for the trouble.

1
  • Are you sure? I've done some quick test with an array and it seems to work fine... Commented Jul 29, 2011 at 10:36

1 Answer 1

3

The to_json is redundant. I just tested it and with works with some similar code here using the syntax:

format.json { render :json => @tasks, :include => [:author] }

This is rails 3.0.7. This is also assuming that author is set as a belongs_to of Task.

Sign up to request clarification or add additional context in comments.

4 Comments

Hum ... In fact this works but only for the first object of the array :/ Other objects do not have the author object.
Bizarre. My example here has a huge list of items, and each has it's belongs_to embedded as appropriate.
Something that might be useful : I am using MongoDB ... :/
Oooh, interesting. So you're not using ActiveRecord. That may make the difference, but I'm not sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.