Ben
Ben

Reputation: 31

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

Upvotes: 3

Views: 136

Answers (2)

Pan Thomakos
Pan Thomakos

Reputation: 34350

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])

Upvotes: 4

apneadiving
apneadiving

Reputation: 115531

Make:

params["post"].merge!({"user_id" => your_variable})

Anyway, Dogbert asked you an excellent question.

Upvotes: 0

Related Questions