Rails を学習するための小さなブログ アプリを作成しています。ユーザーはログインし、投稿を作成し、他のユーザーの投稿にコメントできます。現在、「コメントを追加」ページに Ajax を追加していますが、途中で設計上の問題が発生しました。ページ フローは次のようになります。
# post section
:post.title here
:post.username here
:post.created_at here
:post.body here
# comments section (sorted by date of creation):
:number of comments here
:first comment
:second comment
...
:last comment
# add comment section
:text_area here
:submit button here
問題点:
1 - コメントは作成日順にソートされるため、ajax 呼び出しによって新しいコメントがページの上部に追加されます。並べ替えの動作を変更すると、ajax コードが壊れます。
2 - コメントdivには、.odd、.even、または .admin の 3 つの css クラスを含めることができます (コメントが管理者ユーザーによって作成された場合は、奇数/偶数サイクルまたは管理者を適用します)。現在、これらのクラス名をハードコーディングし、if を使用して正しい名前を取得しています。これも悪いです。css クラス名を変更すると、ajax コードが壊れます。
どうすればこれらのことを回避できますか、または少なくとも改善できますか? これが私のcreate.js.erbです:
var div = $('#comments_div');
var comment_class = div.children().first().attr('class')
var new_class;
<% if current_user.admin == 1 %>
new_class = 'comment_body_admin'
<% else %>
if (comment_class === 'comment_body_odd')
new_class = 'comment_body_even'
else
new_class = 'comment_body_odd'
<% end %>
var new_div = $('#comments_div').prepend("<%= j render @comment %>");
new_div.children().first().attr('class', new_class)
助けてくれてありがとう!