LoginSignup
mako1111
@mako1111 (mako chan)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Action Cableでコメント投稿後、投稿時間を表示したい

解決したいこと

Action Cableでコメント投稿後、投稿時間を表示したい
現在、コントローラーからdataとして@commentの情報を取得し、jsファイルで記述。
一旦、通常動作では日付を表示するようにしていますが、jsで同様の動作を期待して
${data.content.created_at.to_s(:datetime_jp) }の様に記述すると
コンソール上で記述エラーになっています。
解決方法を教えて下さい泣

発生している問題・エラー

SyntaxError: /Users/max/suketto/app/javascript/channels/message_channel.js: Unexpected token (15:55)

該当するソースコード

#app/views/comments/index.html.erb
<!-- コメント内容(2件) ------------------------------------------------------------------>
#app/views/comments/index.html.erb
<%= @comments.count %>件のコメント
<h6 class="more" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">もっと見る....</h6>
<% @comments.first(2).each do |comment| %>
  <% unless comment.id.nil? %>
    <li class="comment-container">
        <div id="comment-box">
            <div class="comment">
              <div class="comment-nickname">
                <p><%= link_to "@#{comment.user.nickname}", user_path(comment.user.id) %></p>
              </div>
                <div id="comment-entry">
                    <span style="font-weight:bold;"><%= comment.content %></span>
                    &nbsp;<%= comment.created_at.to_s(:datetime_jp) %>
                    <% if comment.user == current_user %>
                        <%= link_to post_comment_path(comment.post_id, comment.id), method: :delete do %>
                            &nbsp;<button id="<%=comment.post.id%>" class="delete-btn">削除</button>
                        <% end %>
                    <% end %>
                </div>
            </div>
        </div>
    </li>
  <% end %>
<% end %>
<!-- コメント内容(3件目以降) ------------------------------------------------------------------>
    <div class="collapse" id="collapseExample">
            <% @comments.offset(2).each do |comment| %>
              <% unless comment.id.nil? %>
                <li class="comment-container">
                    <div class="comment-box">
                        <div class="comment-text">
                            <p><%= link_to "@#{comment.user.nickname}", user_path(comment.user.id) %></p>
                            <div class="comment-entry">
                                <span style="font-weight:bold;"><%= comment.content %></span>
                                &nbsp;<%= comment.created_at.to_s(:datetime_jp) %>
                                <% if comment.user == current_user %>
                                  <%= link_to post_comment_path(comment.post_id, comment.id), method: :delete do %>
                                  &nbsp;<button id="<%=comment.post.id%>" class="delete-btn">削除</button>
                                <% end %>
                            <% end %>
                        </div>
                    </div>
                </div>
            </li>
          <% end %>
        <% end %>
    </div>
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    #投稿に紐づいたコメントを作成
    @comment = @post.comments.build(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
      ActionCable.server.broadcast 'message_channel', content: @comment, user: @comment.user
    end
  end

  def destroy
    @post = Post.find(params[:post_id])
    @comment = Comment.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post.id)
  end

  private
  def comment_params
    params.require(:comment).permit(:content, :post_id, :user_id).merge(user_id: current_user.id)
  end
end
#app/javascript/cannels/message_channel.js
import consumer from "./consumer"

consumer.subscriptions.create("MessageChannel", {
  connected() {
    // Called when the subscription is ready for use on the server
  },

  disconnected() {
    // Called when the subscription has been terminated by the server
  },

  received(data) {
    const html = `<p><a href="/#/">@${data.user.nickname}</a></p>
                  <span style="font-weight:bold;">${data.content.content}</span>
                  &nbsp;${data.content.created_at.to_s(:datetime_jp)  }`;

    const messages = document.getElementById('comment-box');
    const newMessage = document.getElementById('comment_content');
    messages.insertAdjacentHTML('beforebegin', html);
    newMessage.value='';
  }
});
#config/initializers/time_formats.rb
Time::DATE_FORMATS[:datetime_jp] = '%Y年 %m月 %d日 %H時 %M分'

自分で試したこと

一旦、通常動作では日付を表示するようにしていますが、jsで同様の動作を期待して
${data.content.created_at.to_s(:datetime_jp) }の様に記述すると
コンソール上で記述エラーになっています。

0

1Answer

${data.content.created_at.to_s(:datetime_jp) } の中のコードが Ruby になっていますが、ここは JavaScript でなければなりません。 ${data.content.created_at} でどうでしょうか。

1

Comments

  1. @mako1111

    Questioner
    @uasiさん ありがとうございます。そちらの記述では最初書いて実行し、結果として.to_s(:datetime_jp)が表示されず、2020年 12月 10日 12時 46分部分が適応されないと思うですが、他の解決方法はありますでしょうか?
  2. Rails 側からデータを送信するときフォーマット済みの日付文字列も送るようにするか、 JavaScript 側で日付をフォーマットするコードを別途書いてください。
  3. @mako1111

    Questioner
    @uasiさん ありがとうございました。解決できました。

Your answer might help someone💌