Topic: Row not saving correctly...

I put this project down for a few weeks and I swear 1/2 of it broke in the time that nobody touched it.

Okay, I have a form to add a book to the database..

class Book < ActiveRecord::Base
  belongs_to :user
  ...
  def before_save
    self.user_id = 1
  end 
end

#BookController
  def add
    @book_conditions = BookCondition.find(:all)
    if request.post?
      @book = Book.new(params[:book])
      @book.user_id = @user.id
      if @book.save
      flash[:notice] = "user_id: #{@user.id}, book.user_id: #{@book.user_id}"
      #  flash[:notice] = "Book Added Successfully"
        redirect_to(:controller => 'user')
      end
    end
  end


@user is created in a before filter
When that flash is displayed.. it shows "user_id: 1, book.used_id: 1" as it should
however, in the database the user_id is being entered as 0..

I've added the book.user_id = 1 in multiple places to try and see where it might be choking, but no matter what it is always put in the db as 0.
Any ideas?

Re: Row not saving correctly...

weird, unless the problem is in your db. like not being set to integer or somthing.

--

Re: Row not saving correctly...

the column is set to int, not null. and there is no problem if I go in a change the value to a 1 manually through the database. And the app behaves as expected if that as done.
But, when I go through the console, on book.update it says true, but does not update the database with the correct user_id...

Re: Row not saving correctly...

How is the @book instance variable being created?

This probably isn't your problem, but I know if you set both the user and user_id, it will prefer the original user you set. For example:

@user = User.find(3)
@book.user = @user
@book.user_id = 1
@book.save
@book.reload.user_id # => 3

At least this is how it used to behave a while ago, not sure if the behavior has changed since.

Railscasts - Free Ruby on Rails Screencasts

Re: Row not saving correctly...

I just figured it out.
I was playing around in the console and when I did
book.user_id = 1 I would get

  #<Book:0x922922 @attributes={....}, @user_id = 1>
  #and when I tried to do
  book.attributes.user_id = 1
  #i got an error saying user_id= method unknown

basically I traced it down to me doing this for some reason:
  attr_accessor :user_id
  attr_accessible :user_id