Creating a Scope that joins user_id with the User Table (user.id) — Rails 3

Hello, I’m using Rails 3 with devise.

I have a table books which has a column for user_id, which is related
to the Users table (user.rb) (FK)

I’m trying to create a Scope that shows all the books along with the
user’s email address (Books joined to Users)
Example: Title, Content, User.Email

class Book < ActiveRecord::Base
scope :personal, proc {|user| where(:user_id => user.id) }
end

Can you help me understand why this is erroring with: “Called id for
nil, which would mistakenly be 4 – if you really wanted the id of
nil, use object_id”

thanks

Are you passing the argument when calling Book.peronal? I think it
expects something like this Book.personal(User.first) – you can
replace User.first by any instance of the class User.

you are not passing the user post the controller code

Ok, so I can do something like this:
scope :expandedvv, Book.joins(:user)

Which has the query (from the dev log) showing:
SELECT “books”.* FROM “books” INNER JOIN “users” ON “users”.“id” =
“books”.“user_id” ORDER BY books.created_at DESC

Problem is it isn’t selecting the fields from the User table that I
need, user.name

Ideas?

While you could change your scope to:

scope: expandedvv, Book.select(‘books.*, users.name’).joins(:user)

You could also use (assuming you’ve correctly defined the
relationships between your book and user models) the activerecord
functionality to display the associated user’s info in your output,
for example, while iterating through your books using “@books.each do |
book|”, you could easily output related user info with book.user.id
and book.user.name.

Thanks looks like I was confusing this.

What I want is to output a query that consists of books joined to the
used, example data row:
book.id, book.name, book.content, user.name, user.id

Right now in Rails everything is just one table, I haven’t learned how
to do joins. How is that done, is that with scopes?