[英]I just don't understand how this RoR works (upvote downvote function)
我正在學習 RoR,但我不明白下面的代碼是如何工作的。 有人可以解釋一下嗎? 我試圖理解但不知道我想念什么。 特別是,我不明白的是
為什么我們需要 post_id 而我們有 vote.post_id?
為什么我們需要upvote(布爾值)?
@success 的作用是什么?
def create
vote = Vote.new
post_id = params[:post_id]
vote.post_id = params[:post_id]
vote.upvote = params[:upvote]
vote.account_id = current_account.id
existing_vote = Vote.where(account_id: current_account.id, post_id: post_id)
respond_to do |format|
format.js do
if existing_vote.size > 0
existing_vote.first.destroy
else
@success = if vote.save
true
else
false
end
end
@post = Post.find(post_id)
render 'votes/create'
end
end
end
def score
if self.upvotes > 0 || self.downvotes > 0
self.upvotes > 0 ? (self.upvotes - self.downvotes) : (self.downvotes * -1)
else
0
end
end
$(function () {
$(".vote").on("click", ".upvote", function () {
let post_id = $(this).parent().data("id"),
is_upvote = $(this).hasClass("upvote")
console.log("clicked " + post_id );
$.ajax({
url: "post/vote",
type:'POST',
data: { post_id: post_id, upvote: is_upvote },
success: function(){
console.log("success");
}
});
});
});
<div id="vote-actions-<%= post.id%>" class="vote" data-id="<%= post.id%>" >
<div class="fa fa-arrow-up upvote"> </div>
<div class="font-weight-bold score"><%= post.score%></div>
<div class="fa fa-arrow-down downvote"> </div>
</div>
$("#vote-actions-<%=@post.id%> .score").text(<%= @post.score%>)
看起來post_id
只是給你一個簡寫,所以你不必在任何地方重新輸入params[:post_id]
。
upvote
似乎有點多余,因為點擊處理程序只會對帶有.upvote
class 的項目進行操作。 我可能是錯的,但在我看來,您可以輕松刪除多余的投票檢查並將您的數據替換為{ post_id: post_id, upvote: true }
。 是否有互補的否決票 function,或者這是為了在投票狀態之間切換?
@succes
在這種情況下似乎也無關緊要,除非它在視圖中的其他地方使用; 我不認為它有直接的目的。
一一解答你的疑惑:
我們正在創建一個 class 投票的新實例,並將 params 值分配給它的 post_id 屬性。
因為我們在這里使用可能的值 0 和 1 處理切換條件,所以代碼的 upvote 為 bool,它也可以根據需要更改為 Int。
@ 引用一個“實例變量”,它可用於“創建”方法的視圖部分或可用於 flash 消息等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.