我一直在关注这个教程https://www.youtube.com/watch?v=TKIbtbYyRdE&list=PL6SEI86zExmvb4qjVHJWrKRQrKjWksQ81&index=34,然后是它的第二部分 https://www.youtube.com/watch?v=akrXCho2m6Y&list=PL6SEI86zExmvb4qjVHJWrKRQrKjWksQ81&index=34
我受够了试图找出问题出在哪里,
<%= link_to "Connect", connections_path, class:"btn btn-primary", data: { controller:"connections", turbo_method: :post, requester_id: current_user.id, connected_id: user.id, connections_target:"connection" } %>
上面的link_to使用StimulusJS控制器"连接",它应该执行POST请求
Connections_Controler.js
import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="connections"
export default class extends Controller {
static targets = ["connection"];
connect() {}
initialize() {
this.element.setAttribute("data-action", "click->prepareConnectionParams");
}
prepareConnectionParams(event) {
event.preventDefault();
this.url = this.element.getAttribute("href");
const element = this.connectionTarget;
const requesterId = element.dataset.requesterId;
const connectedId = element.dataset.connectedId;
const connectionBody = new FormData();
connectionBody.append("connection[user_id]", requesterId);
connectionBody.append("connection[connected_user_id]", connectedId);
connectionBody.append("connection[status]", "pending");
console.log("Connection Body:", connectionBody);
fetch(this.url, {
method: "POST",
headers: {
Accept: "text/vnd.turbo-stream.html",
"X-CSRF-Token": document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content"),
},
body: connectionBody,
})
.then((response) => response.text())
.then((html) => Turbo.renderStreamMessage(html));
}
}
之后,我有ConnectionsController.rb
class ConnectionsController < ApplicationController
before_action :authenicate_user!
def create
Rails.logger.debug "Params received: #{params.inspect}"
@connection = current_user.connections.new(connection_params)
@connector = User.find(connection_params[:connected_user_id])
respond_to do |format|
if @connection.save
format.turbo_stream {
render turbo_stream:
turbo_stream.replace(
"user-connection-status",
partial: "connection/create",
locals: { connector: @connector }
)
}
end
end
end
private
def connection_params
params.require(:connection).permit(:user_id, :connected_user_id, :status)
end
end
当我点击该链接时,它在控制台中显示错误400错误的开机自检请求,并刷新页面.
它不起作用,所以我使用了RAIS.LOGER.DEBUG"PARAMS RECEIVED:#{PARACES INVIST}"
因此在终端日志(log)中显示没有发送参数接收到的参数:#<ActionController::Parameters {"controller"=>"connections", "action"=>"create"} permitted: false>