Hi…I am only 1 day into Rails, so please forgive me if this is a
lame question!
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
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: [
{
…
},
{
…
}
]
}
]
But that does’t work. How can I achieve this?
Thanks in advance!
On Aug 27, 8:35am, John D. [email protected] wrote:
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:
Well you what you get back is an array of projects where the book
objects have already been fetched fro the database
If you call to_json(:include => :books) then you should get output
pretty similar to what you’ve described.
Fred
That did the trick! Thanks!
But, I am sorry I did not get your explanation. Forgive me, I am very
new to Ruby and Rails. Could you please explain why it didn’t work
before, and why it worked your way?
On Aug 27, 7:47am, Frederick C. [email protected]
Also, in my controller, I’d like to call the parent controller’s
method to format my json in a certain way…So instead of this:
respond_to do |format|
format.json { render :json => @projects.to_json(:include =>
[:apps]) }
end
I’d like to do something like this:
result =
respond_to do |format|
format.json { render :json =>
some_method_in_parent_controller(result) }
end
So all my other controllers that subclass this parent application
controller can pass data to this parent controller’s method and format
the data in a particular way.
How do I achieve this? Please help! Thanks!
On Aug 27, 7:47am, Frederick C. [email protected]