2012-02-06 91 views
1

以下控制器執行以下操作:終端說視圖已經呈現,但它並不實際在瀏覽器中呈現?

如果當前用戶的ID存在於其中一個投票實例的user_id屬性中,則當前用戶將被重定向到此頁面,並通知他他或他已投票。如果沒有,投票將被投射並呈現views/votes/vote_up.js.erb

votes_controller.erb:

class VotesController < ApplicationController 
    def vote_up 
    @post = Post.find(params[:id]) 

    if @post.votes.exists?(:user_id => current_user.id) 
     redirect_to @post, notice: 'You already voted' 
    else 
     @vote = @post.votes.create(:user_id => current_user.id, :polarity => 1) 
     respond_to do |format| 
     format.js 
     end 
    end 
    end 
end 

的意見/職位/ show.html.erb:

<div class="post-<%[email protected]%>"> 
    <h3><span class="vote-count"><%= @post.votes.count %></span>votes</h3><br /> 
    <%= link_to "Vote Up", vote_up_path(@post), :remote => true, :class => "vote-up" %><br /> 
</div> 

一切正常,除了確定用戶不被重定向和通知沒有出現。我剛剛得到這個通知在終端:

CACHE(0.0ms)選擇 「用戶」 * FROM 「用戶」 WHERE 「用戶」, 「ID」= 2 ORDER BY渲染users.created_at ASC LIMIT 1。文章/內部佈局/應用(386.5ms)show.html.erb 完成200 OK在428ms(瀏覽次數: 416.5ms | ActiveRecord的:7.3ms)

任何建議,以解決這一問題? (順便說一句,除非here(how),它更易於使用嗎?

回答

2

重定向不起作用,因爲您通過Ajax調用vote_up方法。您應該使用javascript顯示通知,就像您在該用戶還沒有投票

你可以做這樣的事情:。

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 

然後在您的.erb.js文件,這取決於@notice和是否空白或不發回的javascript

<% unless @notice.blank? %> 
    // javascript to display @notice 
<% end %> 

<% unless @vote.blank? %> 
    // javascript to increase vote count 
<% end %> 
+0

你的意思是創建另一個'js.erb'文件?對不起,我是Rails初學者。它在控制器中的外觀如何? – alexchenco 2012-02-06 07:38:15

+0

也許你可以使用相同的'.js.erb'文件。 – Mischa 2012-02-06 07:50:51

+0

你能否給我一個如何做到這一點的提示? – alexchenco 2012-02-06 08:05:17

相關問題