hi, 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: self.book = 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 fine. can someone please clear this up? thanks!
on 2007-05-07 01:21
on 2007-05-07 01:46
My guess is that it's because you are using self in the User class. Try: @book = Book.find_by_id(b_id)
on 2007-05-07 02:01
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).
on 2007-05-07 02:43
Hi Gabriel, you guessed right...that was my mistake...it 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: <%= current_user.book %> can i not access relationships this way?
on 2007-05-07 02:49
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 current_user.book.name or current_user.book.title for example.
on 2007-05-07 03:04
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.... thanks!