Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to subscribe to a channel in a Rails Action Cable consumer.
Ruby on Rails
App.cable.subscriptions.create({ channel: "ChatChannel" }, { received(data) { console.log([1]); } });Attempts:
3 left
💡 Hint
Common Mistakes
Using 'message' instead of the parameter name 'data'.
Trying to log 'this' which refers to the subscription object.
✗ Incorrect
The received callback receives the data sent from the server, so logging 'data' shows the real-time message.
2fill in blank
mediumComplete the code to broadcast a message to a channel from the Rails server.
Ruby on Rails
ActionCable.server.broadcast("chat_channel", [1]: "Hello, world!")
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'data' which is not descriptive enough.
Using 'text' or 'content' which are valid but less common keys.
✗ Incorrect
The broadcast method sends a hash with keys and values. Using 'message' as the key is common to represent the content.
3fill in blank
hardFix the error in the subscription identifier to correctly subscribe to the channel.
Ruby on Rails
App.cable.subscriptions.create({ channel: [1] }, { received(data) { console.log(data); } });Attempts:
3 left
💡 Hint
Common Mistakes
Using unquoted identifiers causing syntax errors.
Using snake_case string instead of CamelCase string.
✗ Incorrect
The channel name must be a string matching the channel class name, so it needs to be quoted exactly as "ChatChannel".
4fill in blank
hardFill both blanks to create a subscription and perform an action when connected.
Ruby on Rails
App.cable.subscriptions.create({ channel: [1] }, { connected() { console.log([2]); } });Attempts:
3 left
💡 Hint
Common Mistakes
Using boolean true instead of a string message.
Using wrong channel name format.
✗ Incorrect
The subscription must specify the channel name as a string, and the connected callback can log a confirmation message like 'Subscribed!'.
5fill in blank
hardFill all three blanks to broadcast a message with a dynamic user and content.
Ruby on Rails
ActionCable.server.broadcast("chat_[1]", { user: [2], message: [3] })
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'channel' instead of 'room' in the channel name.
Not quoting the message string.
Using an undefined variable for user.
✗ Incorrect
The broadcast targets a specific chat room, so 'room' is used in the channel name. The user is the current user's name, and the message is a string.
