Search code examples
ruby-on-railsposts

Rails: Automatically add username to new post


In my posts controller, I am using the following to see the user ID's of different posts made by students:

def new
  @post = current_user.posts.build
end

This is very useful. However, it would be more useful if I can see their names and usernames too. Right now I am making students manually type in their name.

How can you make new posts automatically grab the logged in user's username and name?


Solution

  • To see the user's username and name associated with the @post, you can do:

    username = @post.user.username
    name     = @post.user.name
    

    You should always go and ask the user of @post for the attributes that belong to the user.