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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With