Lee Terng Gio

Joined

2,360 Experience
3 Lessons Completed
1 Question Solved

Activity

Posted in Group Chat with ActionCable: Part 7 Discussion

I've tried to use if else statement, and display a delete link next to the message, when I submit a message, the delete link won't display, and I have to refresh the page. It seems like if else statement doesn't work in actioncable.

I've tried to use if else statement, and display a link next to the message, when I submit a message, the link won't display, and I have to refresh the page. It seems like if else statement doesn't work in actioncable.

Posted in How to use Hotwire in Rails Discussion

How to add auto scrolling when adding a post?

Posted in Hotwire Modal Forms Discussion

I have two models, Post and Comment, the validation message doesn't show up when creating a comment. the rest are working fine except the validation doesn't show up.

Posted in How to use Hotwire in Rails Discussion

I have an issue when I submit an empty for the second time. If I submit the empty field for the first time, the validation displays, then if I submit again with empty field, the submit button is then disabled. How to solve that?

Posted in How to initialize datepicker in stimulus controller?

I'm using datepicker and turbo frame. The datepicker is broken when the frame is replaced. I'm doing turbo:load in javascript file, it works when navigating between pages, but it will be broken when the form is replaced. I'm thinking to initialize datepicker in stimulus controller but I'm not familiar with stimulus. There aren't many documentation on stimulus, any idea?

Posted in How to use Hotwire in Rails Discussion

I have a datepicker in my form, and it's broken when the form is replaced. How to solve that issue?

Posted in Rails 5.1 - View doesn't update on ActionCable

When I try to post a comment, the comment was saved to database and everything seems fine in the console log. But the page isn't updated, I have to refresh every time to see the update. Any idea what's wrong?

javascripts/channels/personal_goals.coffee

App.personal_goals = App.cable.subscriptions.create "PersonalGoalsChannel",
connected: ->
disconnected: ->
received: (data) ->
$("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment']
send_comment: (personal_goal_id, comment) ->
@perform "send_comment", {personal_goal_id: personal_goal_id, personal_goal_message: comment}
If I remove [data-personal-goal-id='#{data.personal_goal_id}'] from $("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment'], then the comment is broadcasted to the view, but this is incorrect since the comment would broadcast to every channel.

javascripts/personal_goals.coffee

$(document).on "turbolinks:load", ->

$("#new_comment").on "keypress", (e) ->
if e && e.keyCode == 13
e.preventDefault()
$(this).submit()

$("#new_comment").on "submit", (e) ->
e.preventDefault()

personal_goal_id = $("[data-behavior='comments']").data("personal-goal-id")
personal_goal_message  = $("#comment_personal_goal_message")

App.personal_goals.send_comment(personal_goal_id, personal_goal_message.val())
personal_goal_message.val("")

channels/personal_goals._channel.rb

class PersonalGoalsChannel < ApplicationCable::Channel
def subscribed
current_user.personal_goals.each do |personal_goal|
stream_from "personal_goals:#{personal_goal.id}"
end
end

def unsubscribed
stop_all_streams
end

def send_comment(data)
@personal_goal = PersonalGoal.find(data["personal_goal_id"])
comment = @personal_goal.comments.create(personal_goal_message: data["personal_goal_message"],user: current_user)
MessageRelayJob.perform_later(comment)
end

end
views/comments/_comment.html.erb

views/personal_goals/show.html.erb

<div class="chat-discussion" id="chatbox" data-behavior="comments" data-personal-goal-id="<%= @personal_goal.id %>">


                    <!--all message-->
                    <% @comments.each do |comment| %>
                      <%= render comment %>
                    <% end %>

        </div>

        <div class="chat-message-form">

                        <!--new message-->

         <%= form_for ([@personal_goal, @comment]) do |f| %>
         <div class="form-group">
                <%= f.text_field :personal_goal_message, class: 'form-control', placeholder: 'Your message' %>
            </div>
         <% end %>

         </div>

jobs/message_relay_job.rb

class MessageRelayJob < ApplicationJob
queue_as :default

def perform(comment)
ActionCable.server.broadcast "personal_goals:#{comment.personal_goal.id}", comment: render_comment(comment)
end

private

def render_comment(comment)
CommentsController.render(partial: 'comments/comment', locals: { comment: comment })
end

end
Console log when submitting a comment:
[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] [ActionCable] Broadcasting to personal_goals:69: {:comment=>"

\n \n \n \n
\n [email protected] \n \n \n hello\n \n
\n
"}
[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] Performed MessageRelayJob (Job ID: 6919f9ee-3601-4f88-873e-503e0107dbef) from Async(default) in 13.98ms
[ActionCable] [User 1] PersonalGoalsChannel transmitting {"comment"=>"

Posted in Rails 5.1 - View doesn't update on ActionCable

When I try to post a comment, the comment was saved to database and everything seems fine in the console log. But the page isn't updated, I have to refresh every time to see the update. Any idea what's wrong?

javascripts/channels/personal_goals.coffee

App.personal_goals = App.cable.subscriptions.create "PersonalGoalsChannel",
connected: ->
disconnected: ->
received: (data) ->
$("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment']
send_comment: (personal_goal_id, comment) ->
@perform "send_comment", {personal_goal_id: personal_goal_id, personal_goal_message: comment}
If I remove [data-personal-goal-id='#{data.personal_goal_id}'] from $("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment'], then the comment is broadcasted to the view, but this is incorrect since the comment would broadcast to every channel.

javascripts/personal_goals.coffee

$(document).on "turbolinks:load", ->

$("#new_comment").on "keypress", (e) ->
if e && e.keyCode == 13
e.preventDefault()
$(this).submit()

$("#new_comment").on "submit", (e) ->
e.preventDefault()

personal_goal_id = $("[data-behavior='comments']").data("personal-goal-id")
personal_goal_message  = $("#comment_personal_goal_message")

App.personal_goals.send_comment(personal_goal_id, personal_goal_message.val())
personal_goal_message.val("")

channels/personal_goals._channel.rb

class PersonalGoalsChannel < ApplicationCable::Channel
def subscribed
current_user.personal_goals.each do |personal_goal|
stream_from "personal_goals:#{personal_goal.id}"
end
end

def unsubscribed
stop_all_streams
end

def send_comment(data)
@personal_goal = PersonalGoal.find(data["personal_goal_id"])
comment = @personal_goal.comments.create(personal_goal_message: data["personal_goal_message"],user: current_user)
MessageRelayJob.perform_later(comment)
end

end
views/comments/_comment.html.erb

views/personal_goals/show.html.erb

<div class="chat-discussion" id="chatbox" data-behavior="comments" data-personal-goal-id="<%= @personal_goal.id %>">


                    <!--all message-->
                    <% @comments.each do |comment| %>
                      <%= render comment %>
                    <% end %>

        </div>

        <div class="chat-message-form">

                        <!--new message-->

         <%= form_for ([@personal_goal, @comment]) do |f| %>
         <div class="form-group">
                <%= f.text_field :personal_goal_message, class: 'form-control', placeholder: 'Your message' %>
            </div>
         <% end %>

         </div>

jobs/message_relay_job.rb

class MessageRelayJob < ApplicationJob
queue_as :default

def perform(comment)
ActionCable.server.broadcast "personal_goals:#{comment.personal_goal.id}", comment: render_comment(comment)
end

private

def render_comment(comment)
CommentsController.render(partial: 'comments/comment', locals: { comment: comment })
end

end
Console log when submitting a comment:

[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] [ActionCable] Broadcasting to personal_goals:69: {:comment=>"

\n \n \n \n
\n [email protected] \n \n \n hello\n \n
\n
"}
[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] Performed MessageRelayJob (Job ID: 6919f9ee-3601-4f88-873e-503e0107dbef) from Async(default) in 13.98ms
[ActionCable] [User 1] PersonalGoalsChannel transmitting {"comment"=>"

Posted in Rails 5.1 - View doesn't update on ActionCable

When I try to post a comment, the comment was saved to database and everything seems fine in the console log. But the page isn't updated, I have to refresh every time to see the update. Any idea what's wrong?

javascripts/channels/personal_goals.coffee

App.personal_goals = App.cable.subscriptions.create "PersonalGoalsChannel",
connected: ->
disconnected: ->
received: (data) ->
$("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment']
send_comment: (personal_goal_id, comment) ->
@perform "send_comment", {personal_goal_id: personal_goal_id, personal_goal_message: comment}
If I remove [data-personal-goal-id='#{data.personal_goal_id}'] from $("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment'], then the comment is broadcasted to the view, but this is incorrect since the comment would broadcast to every channel.

javascripts/personal_goals.coffee

$(document).on "turbolinks:load", ->

$("#new_comment").on "keypress", (e) ->
if e && e.keyCode == 13
e.preventDefault()
$(this).submit()

$("#new_comment").on "submit", (e) ->
e.preventDefault()

personal_goal_id = $("[data-behavior='comments']").data("personal-goal-id")
personal_goal_message  = $("#comment_personal_goal_message")

App.personal_goals.send_comment(personal_goal_id, personal_goal_message.val())
personal_goal_message.val("")

channels/personal_goals._channel.rb

class PersonalGoalsChannel < ApplicationCable::Channel
def subscribed
current_user.personal_goals.each do |personal_goal|
stream_from "personal_goals:#{personal_goal.id}"
end
end

def unsubscribed
stop_all_streams
end

def send_comment(data)
@personal_goal = PersonalGoal.find(data["personal_goal_id"])
comment = @personal_goal.comments.create(personal_goal_message: data["personal_goal_message"],user: current_user)
MessageRelayJob.perform_later(comment)
end

end
views/comments/_comment.html.erb

views/personal_goals/show.html.erb

<div class="chat-discussion" id="chatbox" data-behavior="comments" data-personal-goal-id="<%= @personal_goal.id %>">


                    <!--all message-->
                    <% @comments.each do |comment| %>
                      <%= render comment %>
                    <% end %>

        </div>

        <div class="chat-message-form">

                        <!--new message-->

         <%= form_for ([@personal_goal, @comment]) do |f| %>
         <div class="form-group">
                <%= f.text_field :personal_goal_message, class: 'form-control', placeholder: 'Your message' %>
            </div>
         <% end %>

         </div>

jobs/message_relay_job.rb

class MessageRelayJob < ApplicationJob
queue_as :default

def perform(comment)
ActionCable.server.broadcast "personal_goals:#{comment.personal_goal.id}", comment: render_comment(comment)
end

private

def render_comment(comment)
CommentsController.render(partial: 'comments/comment', locals: { comment: comment })
end

end
Console log when submitting a comment:

[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] [ActionCable] Broadcasting to personal_goals:69: {:comment=>"

\n \n \n \n
\n [email protected] \n \n \n hello\n \n
\n
"}
[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] Performed MessageRelayJob (Job ID: 6919f9ee-3601-4f88-873e-503e0107dbef) from Async(default) in 13.98ms
[ActionCable] [User 1] PersonalGoalsChannel transmitting {"comment"=>"

Posted in Rails 5.1 - View doesn't update on ActionCable

When I try to post a comment, the comment was saved to database and everything seems fine in the console log. But the page isn't updated, I have to refresh every time to see the update. Any idea what's wrong?

javascripts/channels/personal_goals.coffee

App.personal_goals = App.cable.subscriptions.create "PersonalGoalsChannel",
connected: ->
disconnected: ->
received: (data) ->
$("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment']
send_comment: (personal_goal_id, comment) ->
@perform "send_comment", {personal_goal_id: personal_goal_id, personal_goal_message: comment}
If I remove [data-personal-goal-id='#{data.personal_goal_id}'] from $("[data-behavior='comments'][data-personal-goal-id='#{data.personal_goal_id}']").append data['comment'], then the comment is broadcasted to the view, but this is incorrect since the comment would broadcast to every channel.

javascripts/personal_goals.coffee

$(document).on "turbolinks:load", ->

$("#new_comment").on "keypress", (e) ->
if e && e.keyCode == 13
e.preventDefault()
$(this).submit()

$("#new_comment").on "submit", (e) ->
e.preventDefault()

personal_goal_id = $("[data-behavior='comments']").data("personal-goal-id")
personal_goal_message  = $("#comment_personal_goal_message")

App.personal_goals.send_comment(personal_goal_id, personal_goal_message.val())
personal_goal_message.val("")

channels/personal_goals._channel.rb

class PersonalGoalsChannel < ApplicationCable::Channel
def subscribed
current_user.personal_goals.each do |personal_goal|
stream_from "personal_goals:#{personal_goal.id}"
end
end

def unsubscribed
stop_all_streams
end

def send_comment(data)
@personal_goal = PersonalGoal.find(data["personal_goal_id"])
comment = @personal_goal.comments.create(personal_goal_message: data["personal_goal_message"],user: current_user)
MessageRelayJob.perform_later(comment)
end

end
views/comments/_comment.html.erb

views/personal_goals/show.html.erb

<div class="chat-discussion" id="chatbox" data-behavior="comments" data-personal-goal-id="<%= @personal_goal.id %>">


                    <!--all message-->
                    <% @comments.each do |comment| %>
                      <%= render comment %>
                    <% end %>

        </div>

        <div class="chat-message-form">

                        <!--new message-->

         <%= form_for ([@personal_goal, @comment]) do |f| %>
         <div class="form-group">
                <%= f.text_field :personal_goal_message, class: 'form-control', placeholder: 'Your message' %>
            </div>
         <% end %>

         </div>

jobs/message_relay_job.rb

class MessageRelayJob < ApplicationJob
queue_as :default

def perform(comment)
ActionCable.server.broadcast "personal_goals:#{comment.personal_goal.id}", comment: render_comment(comment)
end

private

def render_comment(comment)
CommentsController.render(partial: 'comments/comment', locals: { comment: comment })
end

end
Console log when submitting a comment:

[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] [ActionCable] Broadcasting to personal_goals:69: {:comment=>"

\n \n \n \n
\n [email protected] \n \n \n hello\n \n
\n
"}
[ActiveJob] [MessageRelayJob] [6919f9ee-3601-4f88-873e-503e0107dbef] Performed MessageRelayJob (Job ID: 6919f9ee-3601-4f88-873e-503e0107dbef) from Async(default) in 13.98ms
[ActionCable] [User 1] PersonalGoalsChannel transmitting {"comment"=>"

I'm creating a User, Role and UserRole. A user can create a list of roles, and from the new user form, there is a nested form which populate a list of roles created, then the user able to select a role and associated with the new user. I'm able to create a list of roles, but facing problem when creating a nested form in the new user view file.

Here are the models, kindly advise me if relationships are correct.

class User < ApplicationRecord
  has_one :user_role
  has_one :role, through: :user_role
end
class Role < ApplicationRecord
  has_many :user_role
  has_many :user, through: :user_role
end
class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

User controller. I'm not sure if my controller is correct:

def new
  @user = User.find_by_id(params[:id])
    @user = @current_user.account.users.new
  @user = @current_user.build_user_role
end

def create
    @user = User.find_by_id(params[:id])                
    @user = @current_user.account.users.create_with_password(user_params)
if @user.save
  redirect_to users_path
else
  render 'new'
end

private
def user_params
  params.require(:user).permit(:id, :email, :password, :password_confirmation, :admin, :owner, user_role_attributes: [:user_id, :role_id])
end

end

Below is new user form:

<%= form_for(@user, remote: true) do |f| %>

<%= f.text_field :email, class: "form-control", autofocus: true, autocomplete: "off" %>
<%= f.check_box :admin, class:"checkbox" %>
<%= f.check_box :owner, class:"checkbox" %>

<%= f.fields_for :user_role do |ff| %>
<!-- I don't know how to create a select dropdown to populate a list of roles that have been created -->
<% end %>             

<%= f.button "Create",  class: "btn btn-success" %>

<% end %>

I'm implementing Switchery button in my Rails app and Turbolinks is on. When I navigate to another page, and then click the back button, the button is being duplicated.

Here is my Javascript code:

$(document).on('turbolinks:load', function() {
var elem = document.querySelector('.js-switch');
var switchery = new Switchery(elem, {className:"switchery switchery-small"});
});

Html view:
<b>Assign as administrator?<span> <%= f.check_box :admin, class:"js-switch" %></span></b>

Screenshot: ![https://i.stack.imgur.com/ePJdk.png]

So how can i handle this problem ?

I'm implementing Switchery button in my Rails app and Turbolinks is on. When I navigate to another page, and then click the back button, the button is being duplicated.

Here is my Javascript code:

$(document).on('turbolinks:load', function() {
var elem = document.querySelector('.js-switch');
var switchery = new Switchery(elem, {className:"switchery switchery-small"});
});

Html view:
<b>Assign as administrator?<span> <%= f.check_box :admin, class:"js-switch" %></span></b>

Screenshot: ![https://i.stack.imgur.com/ePJdk.png]

So how can i handle this problem ?

I'm implementing Switchery button in my Rails app and Turbolinks is on. When I navigate to another page, and then click the back button, the button is being duplicated.

Here is my Javascript code:

$(document).on('turbolinks:load', function() {
var elem = document.querySelector('.js-switch');
var switchery = new Switchery(elem, {className:"switchery switchery-small"});
});

Html view:
<b>Assign as administrator?<span> <%= f.check_box :admin, class:"js-switch" %></span></b>

Screenshot: ![https://i.stack.imgur.com/ePJdk.png]

So how can i handle this problem ?

Posted in Switchery toggle button duplicated using Turbolinks

I'm implementing Switchery on my Rails app, and I'm also using Turbolinks. Everything works fine and the switchery is working except when I click to another page and then click the back button, the switchery icon actually duplicated and show twice. How do I destroy when navigating back to the page?

Here is the JavaScript code:

var ready;
ready = function() {
    var elem = document.getElementById('js-switch');
    var switchery = new Switchery(elem, {className:"switchery switchery-small"});

};
$(document).on('turbolinks:load', ready);

I'm implementing Switchery on my Rails app, and I'm also using Turbolinks. Everything works fine and the switchery is working except when I click to another page and then click the back button, the switchery icon actually duplicated and show twice. How do I destroy when navigating back to the page?

Here is the JavaScript code:

var ready;
ready = function() {
    var elem = document.getElementById('js-switch');
    var switchery = new Switchery(elem, {className:"switchery switchery-small"});

};
$(document).on('turbolinks:load', ready);

Posted in Group Chat with ActionCable: Part 5 Discussion

Hi Chris, I don't want to use Turbolinks in my app. Is there any way to replace the code?

Posted in Rails actioncable registered connection issue

I'm implementing ActionCable in my Rails app. I'm facing an issue with Registered Connection error. I'm using MongoID in my Rails app.

Here is my connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
   identified_by :current_user

def connect
  self.current_user = find_verified_user
  logger.add_tags "ActionCable", "User #{current_user.id}"
end

protected

def find_verified_user
 current_user = User.find_by(cookies.signed[:user_id])
  if current_user
    current_user
  else
    reject_unauthorized_connection
  end  
end

  end
end

Here is my logs

Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)
MONGODB | [52] localhost:27017 #1 | dashtree_development.find | STARTED | {"find"=>"users", "filter"=>{"_id"=>BSON::ObjectId('5e3f6782f026752069ba5c21')}, "lsid"=>{"id"=><BSON::Binary:0x47104983206780 type=uuid data=0xac31709d0cea4a74...>}}
MONGODB | [52] localhost:27017 | dashtree_development.find | SUCCEEDED | 0.000s
[ActionCable] [User 5e3f6782f026752069ba5c21] Registered connection (#<User:0x00007f09400c49c8>)
[ActionCable] [User 5e3f6782f026752069ba5c21] ChatroomsChannel is transmitting the subscription confirmation
[ActionCable] [User 5e3f6782f026752069ba5c21] ChatroomsChannel is streaming from chatrooms:5e3f6782f026752069ba5c21

There is an issue with Registered connection (#<User:0x00007f09400c49c8>). I'm still unable to find a solution on this.

Posted in Issues with JQuery AtWho

I getting undefined value.
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2021 GoRails, LLC. All rights reserved.