Capture the user who created the message

It should be very simple (I'm new), but I can not find the answer. What is the best way to grab a user id from a session and insert it into the user_id field for a given message?

(User has_many: messages and messages belong to_to: users)

def create

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

end
+3
source share
2 answers

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

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

And suppose you have a model that is configured like this:

class User
  has_many: posts
end

class Post
  belongs_to: user
end

current_user :

current_user.posts.create(params[:post])
+4

:

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

, .

0

Source: https://habr.com/ru/post/1790213/


All Articles