Ich baue eine Rails-Anwendung mit Upvoting- und Downvoting-Funktionalität. Ich möchte, dass die Farbe grün wird, wenn upvotes> 0 sind, und rot, wenn downvotes> 0 sind. Ich habe einen Helfer, der die Seite so darstellt, aber ich möchte, dass sie auf dem Benutzerbildschirm ohne Seitenaktualisierung aktualisiert wird.Ändern Sie die Hintergrundfarbe basierend auf dem aktualisierten Datensatz
index.html.erb
<div class="panel-left">
<%= link_to 'Upvote', upvote_post_path(post), method: :patch, remote: true %>
<br />
<%= link_to 'Downvote', downvote_post_path(post), method: :patch, remote: true %>
<h1 class="<%=number_of_votes(post.vote_count) %>">
<div id="total-votes-<%= post.id %>">
<%= post.vote_count %>
</div>
</h1>
</div>
upvote.js.erb:
// this updates the counter: it works
$("#total-votes-<%= @post.id %>").html("<%= @post.vote_count %>")
//this is what I am not sure of, I hacked it together but it breaks everything (prevents the above from updating) and shows a server error in the console
if($('<%= escape_javascript @post.vote_count) %>') > 0) {
$("<%=escape_javascript number_of_votes(post.vote_count) %>").attr('style', 'background-color: rgb(179, 144, 114)');
} else {
$("<%= escape_javascript number_of_votes(post.vote_count) %>").attr('style', 'background-color: rgb(115, 227, 87)');
};
Beiträge Helfer
module PostsHelper
def number_of_votes(votes)
if votes > 0
'positive-bg'
elsif votes < 0
'negative-bg'
end
end
end
Wie gesagt alles funktioniert gut, außer ich den Hintergrund wollen Ändern Sie die Farben, wenn die Stimmen der Benutzer ausreichen, um @post.vote_count
auf größer als oder kleiner als 0 zu ändern.
Sie sind ein Genie! – tfantina