Rails:如何在文本框中显示连续的用户输入?

时间:2017-03-02 21:35:13

标签: ruby-on-rails

这里的Rails新手。我想为一个rails应用程序构建一个非常基本的聊天机器人(不涉及学习,只需查询用户对DB的输入),并且我试图将问题分解成碎片。

我无法弄清楚如何在同一页面上显示后续用户输入,就像您在消息窗口中看到的那样。

我发现另一篇文章包含以下代码,但是每个连续的输入都会覆盖前一个代码,我假设每次写入实例变量时都会有新请求?

Controller.rb:

class PagesController < ApplicationController
  def home
    if params[:q].present?
     @input = "hello #{params[:q]}!"
    end
  end
end

form:

 <%= form_tag("/home", method: "get") do %>
   <%= text_field_tag(:q, @input) %>
   <%= submit_tag("Submit") %>
 <%= @input %>

此处的另一个目标是我不想将任何用户输入保存到数据库中。我想要聊天会话&#39;临时的,一旦用户导航离开,显示的数据就被丢弃。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Each time a request is sent to your Rails server a new instance of the controller is made. Once a response has been sent, that instance is destroyed along with any instance variables it created. There really isn't any way to persist those previous messages without saving them to the DB. You could possibly try keeping track of each input in an array in params[:q], appending the new message on the end and continually passing that array back and forth between client and server.