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"
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.
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
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.