Forum: Ruby on Rails Problem with Insertion

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
52f692d554f8b5d659feda7aa783d90f?d=identicon&s=25 Avalin Swift (avalin)
on 2009-04-10 20:40
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:

[code=]<%=link_to("Add to Favorites", favorites_url(:favorite =>
{:user_id => @user.id, :room_id => @room.id}), :method => :post)
%>[/code]
In favorites_controller, my create method looks like this:

[code=]def create
    @room = Room.find(:first, :conditions => ['id = ?',
params[:favorite][:room_id]])
    @favorite = Favorite.new(params[:favorite])

    respond_to do |format|

      puts @favorite.room_id
      puts @favorite.user_id

      if @favorite.save
        flash[:notice] = 'Room was successfully added to your
favorites!'
        format.html { redirect_to(rooms_path(@room)) }
        format.xml  { render :xml => @favorite, :status => :created,
:location => @favorite }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @favorite.errors, :status =>
:unprocessable_entity }
      end
    end
  end[/code]
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"

end[/code]
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.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-04-10 20:56
(Received via mailing list)
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.

Fred
This topic is locked and can not be replied to.