Topic: Models with sessions and params

I have a multi user application. Every user have a unique id number. The users are able to post into a database using the model Post. That works great, except that I can't figure out how to add the user's id number into the database and the :id from the current URL. The user id is stored in session[:user_id]

class Post < ActiveRecord::Base
  validates_presence_of :content
 
  def before_create
    self.parent =
    self.user =
    self.timestamp = Time.now
  end
end

I use this form:
<%= error_messages_for 'post' %>
<%= start_form_tag :action => 'newpost', :id => params[:id] %>
<p><label for="post_content">Content</label><br/>
<%= text_area 'post', 'content', "cols" => 60  %></p>
<%= submit_tag "Create" %>
<%= end_form_tag %>

The controller:
def newpost
    if request.get?
      @post = Post.new
    else
      @post = Post.new(@params[:post])
      if @post.save
        flash['notice'] = 'Post was successfully created.'
        redirect_to :action => 'show', :id => params[:id]
      end
    end
  end

How do I set it up so that self.parent will be params[:id] and so that self.user will be session[:user_id]?

Thank you

Re: Models with sessions and params

If you're doing a parent/child model between posts you should look into acts_as_tree.

As for the user/post relationship, post should belongs_to :user, and the column in the posts table should be "user_id".

As for getting the values set in your Post object before going into the database, I think you should just assign those in your controller's newpost method before saving.

On a related note, if you change your timestamp column to "created_at", it will update the time automatically on creation and you won't have to worry about setting it yourself.

vinnie - rails forum admin