Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing which user created a post

This must be very basic (I am a beginner), but I can't find the answer. What is the best way to capture the user id from the session and stick it into the user_id field for a given post?

(A user has_many :posts and posts belongs_to :users)

def create

 @post = Post.new(params[:post])   (<---I want to get the user id from the session into here?)

end
like image 521
Ben Avatar asked Jul 31 '26 19:07

Ben


1 Answers

Assuming you are handling authentication in such a way that you can access the current user using a method call (current_user):

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

And assuming you have a model that is setup kind of like this:

class User
  has_many :posts
end

class Post
  belongs_to :user
end

You can actually use the current_user to create an associated post like this:

current_user.posts.create(params[:post])
like image 177
Pan Thomakos Avatar answered Aug 03 '26 11:08

Pan Thomakos