I have the following models:
require 'books_projects.rb'
class Project < ActiveRecord::Base
has_many :book_to_projects
has_many :books, :through => :book_to_projects
end
require 'books_projects.rb'
class Book < ActiveRecord::Base
has_many :book_to_projects
has_many :projects, :through => :book_to_projects
end
books_projects.rb:
class BookToProject < ActiveRecord::Base
set_table_name "books_projects"
belongs_to :book
belongs_to :project
end
In my projects controller, I am trying to do this:
@projects = Project.find(:all, :include => [:books])
My hope is to get a nested data structure back that looks something like:
projects: [
{
..,
books: [
{
..
},
{
..
}
]
}
]
This doesn’t work. How can I achieve this?
Also, does the above model relationship call for the use of has_and_belongs_to_many in project and book instead of specifying the join table?
Thanks in advance!
Edit 1:
I don’t have a view. This acts like a REST service only. I am doing the following:
def index
@projects = Project.find(:all, :include => [:books])
respond_to do |format|
format.xml { render :xml => @projects }
format.json { render :json => @projects}
end
end
This does not produce the output that I’m looking for (mentioned above).
So turns out that the following works:
Can someone tell me why this works and the one before didn’t?