Forum: Ruby on Rails question about find_by

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
7da4a7b5be7f1e115861a253afb80641?d=identicon&s=25 (Guest)
on 2007-05-07 01:21
(Received via mailing list)

i am new to ruby/rails, and i am struggling with the find_by method.
Heres some background on what i am trying to get done:

I have a User object, and a Book. User has_one Book, and Book
belongs_to User.

basically, i have a combo box which displays all the books, i get the
id the book is stored in, from the form and then in the user model
class, i try and find the according and assign the according book,
with this find method: = Book.find_by_id(b_id)

unfortunately i end up with this error:

Mysql::Error: #42S22Unknown column 'books.user_id' in 'where clause':
SELECT * FROM books WHERE (books.user_id = 1)  LIMIT 1

I dont understand why it is searching the user_id column (which doesnt
exist), rather than id ....

At first, i thought something was wrong with my Book.find_by
statement, but i tried the same line in an ActionMailer, and it worked

can someone please clear this up?

Abe876bf3149e3b2db085e600f5841c6?d=identicon&s=25 (Guest)
on 2007-05-07 01:46
(Received via mailing list)
My guess is that it's because you are using self in the User class.


@book = Book.find_by_id(b_id)
Fc49ff6d82732b73a94be2974b4dd3df?d=identicon&s=25 Gabriel Gironda (Guest)
on 2007-05-07 02:01
(Received via mailing list)
My guess is that the associations are set up wrong. If a User has_one
Book then it will indeed assume there's a user_id column on books. It
may seem slightly unintuitive, but you may want to swap it around - a
User belongs_to a Book, if you have a book_id column on the users
table, and a Book has_one (or has_many) User(s).
7da4a7b5be7f1e115861a253afb80641?d=identicon&s=25 (Guest)
on 2007-05-07 02:43
(Received via mailing list)
Hi Gabriel,

you guessed right...that was my does seem counter
intuitive, but my user has the book id, and my books do not has a
user_id, since a book can belong to many users.

but it still isnt working, this line seems to fail in my rhtml file:

Book: <%= %>

can i not access relationships this way?
Fc49ff6d82732b73a94be2974b4dd3df?d=identicon&s=25 Gabriel Gironda (Guest)
on 2007-05-07 02:49
(Received via mailing list)
Unless you've defined a to_s method on Book, you want to call the
explicit attribute you wish to display the value of - like or for example.
7da4a7b5be7f1e115861a253afb80641?d=identicon&s=25 (Guest)
on 2007-05-07 03:04
(Received via mailing list)
i actually copied the wrong thing. i originally had what you
suggested, but it was failing...after snoopin around a bit...i
realized i accidentally deleted the 'end' at the end of my Book
class....stupid vi....

This topic is locked and can not be replied to.