使用带远程的ajax的Ruby表单:true给出了ActionController :: InvalidAuthenticityToken错误.经典提交没有

 第一偶像 发布于 2023-01-08 13:53

我正在为一个RoR网站写一个聊天页面.我把它全部用HTML编写,我试图用ajax实现它.有一个提交消息的表单.表单标签读取<%= form_for(@chat, remote: true, :authenticity_token => true) do |f| %>

我的整个观点:

  

    
        Battleriskopoloy - Communications
    
    
        

[ . . . Communications . . . ]

<% $messeges.each do |i| %> <% if i[1] == "from" %>

<%= i[0] %>


<% else %>

<%= i[0] %>


<%end%> <%end%>
<%= form_for(@chat, remote: true, :authenticity_token => true) do |f| %> <%= f.text_field :content, id: "compose" %>

<%= f.submit "Send Messege", id: "submit" %> <% end %>

控制器:

class ChatsController < ApplicationController
     $messeges = Array.new(10, " ")
def new
    $messeges = Array.new
    if $ruser != nil
    $messeges = Array.new
    Chat.all.each_with_index do |i, index|
        if i.recipient == current_user.id && i.sender == $ruser.id
            $messeges.push([i.content, "to"])
        end
        if i.recipient == $ruser.id && i.sender == current_user.id
            $messeges.push([i.content, "from"])
        end
    end
    end
    $chat_users = Array.new
    User.all.each do |user|
        if user != nil && current_user != nil
        if user.game_id == current_user.game_id && user.id != current_user.id
            $chat_users.push(user.username)
        end
        end
    end
    @chat = Chat.new
end

def create
    if $ruser != nil
    @chat = Chat.new(chat_params)
    @chat.recipient = $ruser.id
    @chat.sender = current_user.id
    @chat.save
    end
    redirect_to "/comms/new"
end

def flop
    $ruser = User.find(params[:id])
    $messeges = Array.new
    Chat.all.each_with_index do |i, index|
        if i.recipient == current_user.id && i.sender == $ruser.id
            $messeges.push([i.content, "to"])
        end
        if i.recipient == $ruser.id && i.sender == current_user.id
            $messeges.push([i.content, "from"])
        end
    end
    redirect_to "/comms/new"
end

private
    def chat_params
        params.require(:chat).permit(:content)
    end
end

另外,我<%= csrf_meta_tags %>在我的application.html.erb中

我在网上发现了一些关于人们在从ajax切换到html时遇到与rails 4相同错误的其他事情,但这似乎只是因为他们没有:authenticity_token => true包含参数.任何帮助是极大的赞赏.

1 个回答
  • 默认authenticity_token设置为false.所以你需要在你的行中添加这一行application.rb

    config.action_view.embed_authenticity_token_in_remote_forms = true
    

    2023-01-08 13:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有