Currently only authenticated users are able to write to the database, however, we haven't been keeping track of which posts or comments were posted by which user. To do so, we'll need to make an association between users and their posts and comments.

Generate the migration to associate posts with users in the database: rails g migration AddUserRefToPosts user:references
Generate the migration to associate comments with users in the database: rails g migration AddUserRefToComments user:references
Run rake db:migrate
Add a belongs_to :user association to the Post model
Add a belongs_to :user association to the Comment model

Our Post and Comment models are now associated with User. Now we need to update our controllers so that newly created comments are automatically associated with users.

Update the create action in PostsController:
  def create
    respond_with Post.create(post_params.merge(user_id: current_user.id))
Update the create action in CommentsController:
  def create
    comment = post.comments.create(comment_params.merge(user_id: current_user.id))
    respond_with post, comment

Finally, we'll need to update our as_json methods on our models to include user in our JSON responses.

Override the as_json method in Comment to include the user:
  def as_json(options = {})
    super(options.merge(include: :user))
Update the as_json method in Post to include the post and comments' users:
  def as_json(options = {})
    super(options.merge(include: [:user, comments: {include: :user}]))

Let's update the views to display the username of the user associated with each post and comment

Update _home.html to show the poster's username:
    posted by <a ng-href="#/users/{{post.user.username}}">{{post.user.username}}</a>
Update _posts.html to show the commenter's username:
  {{comment.upvotes}} - by {{comment.user.username}}

Now when we create new posts and comments, we should be able to see who created the post or comment!

Challenge Yourself

Throughout this tutorial we've learned how to build an AngularJS app that persists to a Rails backend. By now, you should hopefully have a good understanding of how to use these technologies as well as the ability to make modifications and add new features. If you're looking to sharpen your skills through practice, here are some suggestions on modifications you can add to Flapper News:

  • Only allow users to vote once
  • Implement a 'downvoting' feature
  • Display the number of comments next to each post on the main page.
  • Database/Form validations and error handling.

If you're looking to learn more about using AngularJS, check out the "Learn to build Modern Webapps" tutorial, which teaches you how to use Firebase with AngularJS to build a hosted platform.

We sincerely hope this tutorial has been helpful. If you have any questions, comments, or feedback, feel free to email us at hello@thinkster.io or tweet us at @GoThinkster.


I finished! On to the next tutorial