0
我有一個帖子,評論和投票模型爲什麼此屬性在此html.erb視圖中工作,但不在此其他js.erb視圖(Rails)中?
創建Vote
模型的實例每次(或者與:polarity
+1或-1),它更新後的total_votes
列屬於:
vote.rb:
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
total_average = self.votable.total_votes
self.votable.update_attribute(:total_votes, total_average + self.polarity)
end
end
這是我如何把它在show.html.erb觀點:
示例的<div class="post-<%= @post.id %>">
<h3><span class="vote-count"><%= @post.total_votes %></span> votes</h3><br />
votes_controller.rb:
def vote_up
@post = Post.find(params[:id])
if @post.votes.exists?(:user_id => current_user.id)
@notice = 'You already voted'
else
@vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
end
respond_to do |format|
format.js
end
end
routes.rb中:
get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up'
出於某種原因@ post.total_votes給出0,該列的默認值(是否其實際值爲-1或1),如果它通過Ajax從此文件附加到show.html.erb:
vote_up.js.erb:
<% unless @notice.blank? %>
alert("<%= @notice %>");
<% end %>
<% unless @vote.blank? %>
$('.post-<%[email protected]%> span.vote-count').html('<%= @post.total_votes %>');
$('.post-<%[email protected]%> div.voted-user').html('<% @post.votes.each do |vote| %><%= link_to vote.user.username, vote.user %><% end %>');
<% end %>
任何建議,以解決這一問題?
非常感謝。有效! – alexchenco 2012-02-09 03:23:23