Problem with Insertion


I have a model called Room, and I am trying to allow the user to create
favorites to bookmark certain rooms. The Favorites table contains the
fields “room_id” and “user_id”, and in the view for /rooms/:id I have
the following code:

<%=link_to("Add to Favorites", favorites_url(:favorite => {:user_id =>, :room_id =>}), :method => :post) %>
In favorites_controller, my create method looks like this:

[code=]def create
@room = Room.find(:first, :conditions => [‘id = ?’,
@favorite =[:favorite])

respond_to do |format|

  puts @favorite.room_id
  puts @favorite.user_id

    flash[:notice] = 'Room was successfully added to your

format.html { redirect_to(rooms_path(@room)) }
format.xml { render :xml => @favorite, :status => :created,
:location => @favorite }
format.html { render :action => “new” }
format.xml { render :xml => @favorite.errors, :status =>
:unprocessable_entity }
The two puts statements print out the room ID and user ID correctly, but
in the site itself I get the following error:

SQLite3::SQLException: favorites.user_id may not be NULL: INSERT INTO
“favorites” (“updated_at”, “user_id”, “room_id”, “created_at”)
VALUES(‘2009-04-10 18:04:46’, NULL, NULL, ‘2009-04-10 18:04:46’)

If I manually go into the GUI for SQLite3, I can enter in a new row for
favorites fine, but when I try creating a new Favorite through the
console, I receive an error. My model code looks like this:

[code=]class Favorite < ActiveRecord::Base
belongs_to :room
belongs_to :user

named_scope :for_user, lambda { |user_id| { :conditions => [“user_id =
?”, user_id] }}

attr_accessor :room_id, :user_id
validates_presence_of :room_id, :user_id => “must be filled in”

Any thoughts? I don’t believe it is a problem with the controller since
it is printing the correct values, but I can’t figure out what is wrong
with the model or database.


On 10 Apr 2009, at 19:40, Avalin Swift wrote:

attr_accessor :room_id, :user_id

Don’t do this: you are overwriting the accessors that Active Record
provides with ones that will stick the values in places Active Record
won’t find.