我是自我参照关系的新手,我目前正在通过this教程来建立相互友谊模式。
我已经实现了FriendRequest模型并将其与用户模型相关联:
FriendRequest.rb
class FriendRequest < ApplicationRecord
belongs_to :user
belongs_to :friend, class_name: 'User'
User.rb
class User < ApplicationRecord
has_many :friend_requests, dependent: :destroy
has_many :pending_friends, through: :friend_requests, source: :friend
我在用户的个人资料页面上创建了一个链接,以创建新的好友请求:
<%= link_to 'Add Friend', friend_requests_path, method: :post %>
friend_requests_controller.rb
class FriendRequestsController < ApplicationController
before_action :set_friend_request, except: [:index, :create]
def create
friend = User.find(params[:friend_id])
@friend_request = current_user.friend_requests.new(friend: friend)
if @friend_request.save
render :show, status: :created, location: @friend_request
else
render json: @friend_request.errors, status: :unprocessable_entity
end
end
private
def set_friend_request
@friend_request = FriendRequest.find(params[:id])
end
end
但它会抛出ActiveRecord :: RecordNotFound Couldn't find User with 'id'=
针对该行提出具体问题:friend = User.find(params[:friend_id])
的routes.rb
Rails.application.routes.draw do
...
resources :users
resources :user_sessions, only: [:new, :create, :destory]
get 'login' => 'user_sessions#new'
get 'logout' => 'user_sessions#destroy'
get 'friends/index'
get 'friends/destroy'
resources :friend_requests
end
我已尝试在create
操作和私有方法中更改参数,但我总是得到相同的ActiveRecord错误。
这是来自帖子请求的日志:
Started POST "/friend_requests" for 127.0.0.1 at 2018-04-28 19:36:16 -0400
Processing by FriendRequestsController#create as HTML
Parameters: {"authenticity_token"=>"BWRNktuMbSt6nNWDyloy+t7fwhyd8ITa/P4/7C0zmeCHyEPFQBVe9h2MpdCUC4Od4tjoC5Qg0x4Z6owf+29F9Q=="}
User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 57ms (ActiveRecord: 4.4ms)
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=):
app/controllers/friend_requests_controller.rb:5:in `create'
答案 0 :(得分:1)
在控制器中,您期望params[:friend_id]
,但不会在请求中传递它。
您的链接应该是这样的:
link_to 'Add Friend', friend_requests_path(friend_id: 123), method: :post
或者像这样:
button_to 'Add Friend', friend_requests_path, params: {friend_id: 123}