user_id being saved as NULL... but why?

Hello there,

I have a mini blog in which stores a few bits of info:

- title
- body
- created on
- user_id

If you're logged in, you can enter a comment too.
this stores:

- body
- blogpost_id
- user_id

however. For some reason, the user id when the blog is created is
stored. It is not stored when a user adds a comment, and I wondered if
anyone can spot what i ave missed?

Actions from the Blogpost controller:

def new
    @user = User.find(session[:user_id])
    #@blogpost = Blogpost.new
     @blogpost = Blogpost.create(:body => params[:body], :user_id =>
session[:user_id])

    @cat = Category.find(:all)
    respond_to do |format|
      format.html # new.html.erb
      format.xml { render :xml => @blogpost }
    end
  end

  def create
    @user = User.find(session[:user_id])
    @blogpost = Blogpost.new(params[:blogpost])
    #@blogpost.category_id = (params[:category])

    respond_to do |format|
      if @blogpost.save
        flash[:notice] = 'Blogpost was successfully created.'
        format.html { redirect_to(@blogpost) }
        format.xml { render :xml => @blogpost, :status
=> :created, :location => @blogpost }
      else
        format.html { render :action => "new" }
        format.xml { render :xml => @blogpost.errors, :status
=> :unprocessable_entity }
      end
    end
  end

And then the comment: (this is also in the same controller)

  def comment
    @user = User.find(session[:user_id])
    @blogpost = Blogpost.new
    @blogpost = Blogpost.create(:body => params[:body], :user_id =>
session[:user_id])

     Blogpost.find(params[:id]).comments.create(params[:comment])

     flash[:notice] = "Added your comment"

     redirect_to :action => "show", :id => params[:id]

  end

THe coment does get stored to the database, but the user_id remains
NULL.

Any ideas?

thanks for reading.

This sounds like you don't have auto-increment turned on, on the specific database table. Check that first?
-j

Unless user_id was part of the fields in params[:comment] you don't
seem to be setting the user id on the comment anywhere.

Fred

Hello,

Good point - I have tried to amend the code like below, but i get
errors:

ORIGINAL CODE:
Blogpost.find(params[:id]).comments.create(params[:comment])

AMENDED CODE 1:
Blogpost.find(params[:id, :user_id]).comments.create(params[:comment])
THis returns error: wrong number of arguments (2 for 1)

AMENDED CODE 2:
Blogpost.find(params[:id]).comments.create(params[:comment,:user_id])

THis also returns error: wrong number of arguments (2 for 1)

I'm sure it's quite simple, but can't put my finger on it.. Any ideas
what needs to change?

Many Thanks

You either need to merge your hash of params from the form with the
user_id you want to set or you need to set the user_id on the comment
afterwards.

Fred