2020年3月16日 星期一

ActionCable rails 6 realtime chat app

心得:整個弄完,發現我還有前端的javascript沒有弄熟,主要問題出再不熟悉選擇器。我之前弄過一點jquery跟vue.js但是沒有很熟練的使用,看來要使用javascript去更改網頁內容,還是免不了要知道一點jquery或是vue.js吧

學習的架構很重要,這個actioncable我大概弄了兩天晚上才搞懂,第一天晚上就照著貼程式碼。第二天忽然知道在搞什麼了。
這邊最重要的就是
後端channel
前端javascript


以下是引入的步驟
1.引用javascript套件
2.開channel,
3.在controller裡面接上ActionCable傳值
4.使用javascript去更改html
5.修理bug
影片一,Rails 6教學
https://youtu.be/nRP91C1uX-w
影片二,整套的教學
https://www.youtube.com/watch?v=tyNepRO_ERc

$rails new chat
$cd chat
$git init
$git add .
$git ci -am "init"
$yarn add jquery
$rails g scaffold message content:string
$rails db:migrate
$git ci -am "scaffold message"

ctrlp>route
root "messages#index'

設置jQuery

config/webpack/environment.js增加內容
const webpack = require('webpack')
environment.plugins.prepend('Provide',new webpack.ProvidePlugin({$: 'jquery/src/jquery',jQuery: 'jquery/src/jquery'
})
)

ctrlp>application.js設置jQuery
require('jquery')

$(document).on('turbolinks:load',function(){
  console.log('hello')
})

有看到console.log('hello')就表示jquery設置成功

$rails g channel room
>>>create app/channels/room_channel.rb
>>>create app/javascripts/channels/room_channel.js

ctrlp>room_channel.js
  connected() {
      +console.log("connected")
有看到connected就表示room_channel設置成功

ctrlp>room_channel.rb

  def subscribed
    stream_from "room_channel"
    # stream_from "some_channel"
  end

ctrlp>message_controller.rb

if @message.save
    ActionCable.server.broadcast 'room_channel',content: @message.content
end

ctrlp>room_channel.js
  received(data) {
     console.log('receive data')
    // Called when there's incoming data on the websocket for this channel

ctrlp>index.html.erb
<div id="msg">
</div>

ctrlp>room_chnnel.js
  received(data) {
    $('#msg').append('<div class="message">' + data.content + '</div>')

debug 

有個錯誤,輸入完成的時候,輸入框仍然會保留上一次的輸入結果,想辦法使用jquery解決。

var submit_messages; 設立變數
$(document).on('turbolinks:load,function(){
    submit_messages()
})
submit_messages = function(){
    $('message_content').on('keydown',function(event){
        if(event.keyCode === 13){
            console.log('we hit enter') #檢查有沒有按下enter成功
            $('input').click()
            event.target.value = "" #洗掉內容
            event.preventDefault()   #防止輸入空排
        }
    })
}




沒有留言:

張貼留言

cloud9上面開發rails

 使用IAM身分登入,以免有資安問題。(用admin帳號登入,創建iam使用者,然後在上面的連結登入) 選擇 ubuntu18.04 減少查詢成本。 已經是超級使用者了,sudo 什麼都不需要輸入密碼了。 $ ruby -v  檢查 ruby使用的版本>>2.6.3,...