Real-Time Rails: Implementing WebSockets in Rails 5 with Action Cable
Redis 消息订阅发布简介
https://www.youtube.com/watch?v=81NSa7IhTIc
rails 5 中文
https://mgleon08.github.io/blog/2018/06/21/rails-action-cable/
rails 6 英文
https://medium.com/@jelaniwoods/get-started-with-action-cable-in-rails-6-4c605f93c9b8
$rails new realtimechat> 創造
$yarn add jquery
ctrlp>app/javascript/packs/application.js
插入
require('jquery')
$(document).on('turbolinks:load', function (){
console.log('yeah, we are ready!');
#或是alert('yeah, we are ready!'); 也行
}
ctrlp>app/config/webpack/environment.js
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
)
module.exports = environment
rails g controller landing index
- ctrlp>routes
將首頁設定在landing#index
root "landing#index'
Creat a model Message
- rails g model message content
- rails db:migrate
- rails g controller MessagesController
- rails g channel room>
製造出了
app/channel/room_channel.rb
app/javascript/channels/room_channel.js
- ctrlp>app/channels/room_channel.rb
設定stream
def subscribed
stream_from "room_channel"
end
- ctrlp>app/javascript/channels/room_channel.js
增加一行,使得room_channel接收到資訊的時候,可以在condole.log裡面顯示出data.content。
received(data){
console.log(data.content)
}
- ctrlp>messages_controller.rb
設定controller的連結資料庫的動作
def new
@message = Message.new
end
def create
@message = Message.create(msg_params)
end
private
def msg_params
params.require(:message).permit(:content)
params.require(:message).permit(:content)
end
chrome console的錯誤資訊
info
XHR failed loading: POST "http://localhost:3000/landing/index".>表示有東西沒有連好,照著提示一步一步去拆解到底是哪裡出問題。
沒有留言:
張貼留言