Search code examples
ruby-on-railsdevisecontroller

How to use current user in devise


I'm trying to create a website with rails (6.0.0). i'm using devise library for users sign-up and sign-in system. now my questions is "How to use current user's id for creating the post (user_id is required in post model)."

this is my app/controllers/posts_controller.rb

def create   
   @post = Post.new(post_params)   
   if @post.save   
     flash[:notice] = 'post added!'   
     redirect_to 'posts'   
   else   
     flash[:error] = 'Failed to edit post!'   
     render :new   
   end   
end   

def post_params   
   params.require(:post).permit(:name, :picture, :user_id, :description)   
end   

Solution

  • Use @post = current_user.posts.new(post_params) so activerecord sets the proper user_id.