我一直在关注这个教程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>

推荐答案

您的操作缺少控制器:

this.element.setAttribute("data-action", "click->connections#prepareConnectionParams");
//                                               ^^^^^^^^^^^

Here is another example with Stimulus action params:
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响应.

Ruby-on-rails相关问答推荐

RSpec系统测试无法从工厂访问新创建的记录

使用Rails和RSpec,有没有办法查看操作真正将您带到哪个页面?

如何在 Rails 中声明动态路由范围/命名空间变量?

您如何测试方法调用块内调用的方法,以及使用 rspec 在块内传递给该方法调用的内容

Rails 模型 - 以 ID 作为自定义列的自定义主键

理解 Gemfile.lock:删除 Gemfile.lock 然后再次运行 bundle install 可以吗?

使用 Devise 令牌登录,这是内置的吗?

rails 4.0, rake db:sessions:create

.increment vs += 1

使用 AJAX 向 Rails 发送 Authenticity Token 的正确方法

如何在 ROR (Ruby) 中显示 PDF?

在范围内传递参数

从 Rails 中的控制器调用辅助方法时出现未定义的方法

ActiveRecord 事务中的错误处理?

rbenv:没有 gemsets 生存

我怎样才能看到水豚在失败的黄瓜步骤中发现了什么?

Vagrant上的Rails 4.2服务器端口转发不起作用

rails路由中资源和资源之间的区别?

如何在不触及 updated_at 属性的情况下更新单个属性?

没有UTC的Rails 3默认日期时间格式