开发者

get session data in rails

开发者 https://www.devze.com 2023-01-06 05:47 出处:网络
I\'m new to rails coming from php, and I\'m learning rails 3 with mongodb. I have got to the point where I have an html form post text to mongo, and i can create and login as a user.

I'm new to rails coming from php, and I'm learning rails 3 with mongodb.

I have got to the point where I have an html form post text to mongo, and i can create and login as a user.

In the user login, i create a session with as created by nifty authenticate

session[:user_id] = user.id

now I'm trying to get that user_id from the session when I create a new post so that the post is connected to the user.

in my posts_controller, I have the create function as follows.

def create
    @post = Post.new(params[:post])
    respond_to do |format|
      if @post.save
        format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
        format.xml  开发者_StackOverflow社区{ render :xml => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
end

however, i believe I need to pass the user_id in here, or maybe it would be better to put it in my model.

But attempting any sort of

@user_id = session[:user_id]

hasn't returned anything meaningful. Am I going about this the wrong way?

I've seen posts which describe storing sessions in the database, but I don't really see why this should be necessary for something as simple as just getting the currently logged-in user_id.


If you are just looking to keep track of the user who created the post in your post db? Within the post model a simple:

belongs to: user

should work. As long as you have a user_id field in your post db as well (I'm not exactly sure if this is what you were asking for.)


Take a look at the docs: Nifty Authentication

Nifty Authentication includes a method called current_user (most of the authentication solutions for Rails follow the same naming convention) that will do exactly as it says, get the current user. So, you could do the following:

post.user = current_user

EDIT This can be done only after you create the proper relationship as detailed by Mike.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号