Gists of controller code at bottom of page
I have a simple rails nesting project that I’m practicing with and I’m having an issue that I can’t seem to spot.
When I visit the url: localhost:3000/authors/1/books I get ALL the books – not the books that correspond to the author with an id=1.
Here is some of my code:
I have an Author model and controller, and a Book author and controller:
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
end
The routes file looks like this:
resources :authors do
resources :books
end
Here is the migration for Books:
class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :title
t.integer :author_id
t.timestamps
end
end
def self.down
drop_table :books
end
end
It contains an attribute for author_id
I also have this code in the Books _form.html.erb file:
<div class="field">
<%= f.label :author_id %><br />
<%= f.collection_select(:author_id, Author.all, :id, :first_name) %>
</div>
I am able to choose an author from the drop-down box and save it successfully. The database shows that the author_id is indeed being saved to the corresponding Book model.
When I run rake routes I get this as one of the routes:
author_books GET /authors/:author_id/books(.:format)
But, when I try this url – I just get a listing of ALL books. Not books corresponding to the proper author.
Also, I have my controllers setup to return JSON and when I put localhost:3000/authors.json it returns the proper JSON object, but when I put localhost:3000/authors/1/books.json it returns ‘null‘
Here is a screen shot of my current database listings to show that the data is definitely there:

Can you see anything that may be causing the problem??? I can provide more code if you need it.
EDIT
After running rails console I get the correct data – so I’m not sure why the route is still not working:
irb(main):002:0> Author.find(1).books
=> [#<Book id: 1, title: "Carrie", author_id: 1, created_at: "2012-01-08 21:20:57", updated_at: "201
2-01-08 21:20:57">]
Here is a Gist of complete routes: https://gist.github.com/1580058
Here is the Books controller: https://gist.github.com/1580064
Here is the Authors controller: https://gist.github.com/1580134
Sorry, just realized I miss-worded the original question up top – I’m getting the whole list of Books, not Authors – corrected
You need to show us your index action in the controller. I’m guessing you have Book.all… You need
you also might want
Also in your show method make sure you do this
instead of