Application monitoring that helps developers get it done.
Deploy apps to servers that you own and control.
Now that we have posts set up in our application, it's time to refine the post resource so that it aligns perfectly with Lorem News’ specific needs.
I took some time to write out the expected behavior for posts in Lorem News:
We've made good progress, but there's still work to be done. Let’s jump into our Post controller and refine our logic.
We want unauthenticated users to be able to:
But they should not be able to create, edit, or delete posts.
To allow this, we modify our Post controller to permit unauthenticated access only to index and show:
class PostsController < ApplicationController
allow_unauthenticated_access only: [:index, :show]
end
This ensures that anyone can browse posts, but only signed-in users can interact beyond that.
Setting the Root Route to Show Recent Posts We also ensure that the homepage correctly displays the latest posts by modifying index to return the 50 most recent posts:
def index
@posts = Post.order(created_at: :desc).limit(50)
end
Now, when we visit /, we see exactly what we want—a feed of the latest posts.
Next, we need to prevent unauthorized users from modifying or deleting posts.
We update our Post controller to ensure that only the original author can perform edit, update, or destroy:
before_action :set_post, only: %i[ edit update destroy ]
allow_unathenticated_access only: %i[index show]
private
def set_post
@post = Post.find(params.expect(:id))
raise NotAuthorized unless @post.user == Current.user
end
Defining a Custom NotAuthorized Exception Since NotAuthorized isn’t a built-in Rails exception, we define it inside our ApplicationController:
class ApplicationController < ActionController::Base
NotAuthorized = Class.new(StandardError)
end
This means:
Even though the server now prevents unauthorized actions, we should also hide the buttons in the UI to improve the user experience.
We update our post view (show.html.erb):
<% if @post.user == Current.user %>
<%= link_to "Edit", edit_post_path(@post) %>
<%= link_to "Delete", @post, method: :delete %>
<% end %>
This ensures:
With these changes, we now have:
Let's commit everything.
Now that posts are working securely and correctly, our next step is to add comments to posts. Once we scaffold comments, we’ll focus on polishing the UI for an excellent user experience.