自引用关系互相关注模型开发:FriendRequestsController#show遇RecordNotFound错误
Hey there! Let's break down why you're hitting that ActiveRecord::RecordNotFound error when trying to access the FriendRequestsController#show action. Here are the most common fixes to check:
First, make sure your routes for friend requests are properly defined in config/routes.rb. A typical setup (either standalone or nested under users) would look like this:
# Standalone resource setup resources :friend_requests, only: [:show, :create, :destroy] # Or nested under users (if your app flow ties requests to a user's profile) resources :users do resources :friend_requests, only: [:show, :create] end
If you're using nested routes, your link path needs to include both the user ID and friend request ID (like user_friend_request_path(@user, @friend_request)). For standalone routes, it's just friend_request_path(@friend_request). Double-check that your user page link uses the correct path helper with the right parameters.
show Action in Your Controller Chances are, your show action isn't fetching the record correctly—especially if you want to ensure the current user only accesses their own friend requests. Here's a secure, error-resistant way to write it:
class FriendRequestsController < ApplicationController before_action :authenticate_user! # Ensure the user is logged in first def show # Only fetch friend requests that belong to the current user @friend_request = current_user.friend_requests.find(params[:id]) end end
If you were just using FriendRequest.find(params[:id]), you might be trying to access a request that doesn't belong to the current user (or doesn't exist at all), which triggers the RecordNotFound error. Scoping the query to current_user.friend_requests fixes this.
Make sure the link you're creating passes the correct friend request ID, not a user ID. For example, if you're listing pending requests on a user's page, your ERB should look something like this:
<% @user.pending_friends.each do |friend| %> <% # Grab the specific friend request between the current user and this friend %> <% request = @user.friend_requests.find_by(friend: friend) %> <%= link_to "View Request Details", friend_request_path(request) %> <% end %>
If you accidentally passed a user ID (like friend_request_path(friend)), it'll look for a friend request with that user's ID—which almost certainly doesn't exist, hence the error.
Before digging deeper, verify the record you're trying to view exists in your database. Run this in your Rails console:
# Replace 123 with the ID from your URL FriendRequest.find(123)
If this throws the same error, the record doesn't exist. You'll need to check that your friend request creation flow works correctly (e.g., when a user sends a request, it's saving to the database properly).
内容的提问来源于stack exchange,提问作者tfantina

