提问人:uma 提问时间:11/11/2023 更新时间:11/11/2023 访问量:62
Rails 7 中的 Turbo Streams
Turbo Streams in Rails 7
问:
我一直在关注本教程 https://www.youtube.com/watch?v=TKIbtbYyRdE&list=PL6SEI86zExmvb4qjVHJWrKRQrKjWksQ81&index=34 然后是其第 2 部分 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_controller.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 错误的开机自检请求并刷新页面。
它不起作用,所以我使用了 Rails.logger.debug “Params received: #{params.inspect}”
所以在终端日志中,它说没有发送参数 收到的参数:#<ActionController::Parameters {"controller"=>"connections", "action"=>"create"} permitted: false>
答:
您缺少操作的控制器:
this.element.setAttribute("data-action", "click->connections#prepareConnectionParams");
// ^^^^^^^^^^^
下面是另一个带有刺激动作参数的示例:
https://stimulus.hotwired.dev/reference/actions#action-parameters
# there is no need for `turbo_method: :post` since we're doing our own posting
# `connections_target` is also a bit redundant on a controller element itself
<%= link_to "Connect", connections_path,
data: {
controller: "connections",
connections_requester_id_param: 1,
connections_connected_id_param: 2,
connections_status_param: "pending",
}
%>
// app/javascript/controllers/connections_controller.js
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
connect() {
this.element.setAttribute("data-action", "connections#prepareConnectionParams");
}
prepareConnectionParams(event) {
event.preventDefault();
const { params } = event;
const body = new FormData();
body.append("connection[user_id]", params.requesterId);
body.append("connection[connected_user_id]", params.connectedId);
body.append("connection[status]", params.status);
fetch(this.element.getAttribute("href"), {
method: "POST",
headers: {
Accept: "text/vnd.turbo-stream.html",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
},
body,
})
.then((response) => response.text())
.then((html) => Turbo.renderStreamMessage(html));
}
}
我没有看过教程,只是确保所有^都会导致有用的东西,因为您可以使用常规表单和更少的代码完成相同的操作:
<%= button_to "Connect", connections_path,
params: {
connection: {
user_id: 1,
connected_user_id: 2,
status: "pending",
}
}
%>
这将发送具有相同参数的 TURBO_STREAM POST 请求,并为您处理响应。turbo_stream
评论