简体   繁体   中英

Ruby on rails passing information from session into db

I have been trying to set up a little twitter app to teach myself ruby on rails, i have a log in page that works and stores the user like this

    session[:user_id] = user.id

I can use that in the views, but i am trying to create a relationship based on it so that the tweet, which is created on a new page in in a basic form, is linked to the current session user.

I for some reason can't figure out how to do it.

You can have the current_user (for example) method:

def current_user
  @current_user ||= User.find_by_id(session[:user_id])
end

If you already have this, you can create post with:

@post = current_user.posts.create(params[:post])

You should also check, of course, if any user is signed in before creating post, or you'll have NoMethodError .

参见devise gem https://github.com/plataformatec/devise Devise在视图和控制器中提供了current_user和user_session方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM