Building a Rails Blog: From Request to Published Post
Start with a complete feature
A blog is a useful way to learn Rails because one feature crosses routes, controllers, models, and views. Begin with creating a draft, displaying validation errors, and publishing it. Keep authentication and authorization visible in that flow rather than adding them after the interface is finished.
Make ownership part of the query
Build posts through the signed-in user's association. Never accept user_id from a submitted form. When editing, find the record through that same association so another author's ID cannot grant access.
def create
@post = current_user.posts.build(post_params)
@post.status = :draft
if @post.save
redirect_to @post, status: :see_other
else
render :new, status: :unprocessable_entity
end
end
def post_params
params.require(:post).permit(:title, :body)
end
Separate writing from publication
A valid draft is not necessarily ready for readers. Represent publication as an explicit state transition, and check the actor's permissions on the server. In a moderated blog, the public query should require both published status and approval. A hidden button alone is not an access control.
Check the complete journey
Test that an author can save a draft, cannot edit another author's post, and sees useful errors for a blank title. Verify that an unapproved post never appears in the public listing. These tests protect the behavior readers and authors rely on, even when controller internals change.
Extend the feature only after this path works: add tags, rich text, and background indexing as separate changes with clear responsibilities.
Tienbob
リアクション
コメント
サインイン して会話に参加しましょう。