2013-03-25 117 views
-2

我寫了controlloer爲什麼這些代碼無法按預期工作?

class NotificationsController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    @notification = current_user.notification 
    if @notification.unread == 0 
     redirect_to root_path 
    else 
     @notification.unread == 0 
     @notification.save 
    end 
    end 
end 

,我希望@notification.unread爲0後顯示指數page.But不能實際工作。 如何更改這些代碼以使其正常工作。

希望你能幫助我,非常感謝:)

回答

2

我不知道我完全理解你要做什麼,但你打電話==兩次,這是一個比較運算符,我認爲在第二部分中你要設置的值,所以你應該使用=僅

喜歡這個

class NotificationsController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    @notification = current_user.notification 
    if @notification.unread == 0 
     redirect_to root_path 
    else 
     @notification.unread = 0 
     @notification.save 
    end 
    end 
end 
2

嘗試使用的@notification.unread = 0代替@notification.unread == 0

+0

哦,我做出了這樣的嚴重錯誤。 :( – hsming 2013-03-25 15:27:02

0
else 
     @notification.unread = 0 
     @notification.save 
    end 

@ notification.unread == 0不會改變屬性的值。 :)

0

它總是一個好主意,業務邏輯移動到的車型,所以你可以這樣寫

class Notification < ActiveRecord::Base 

    def unread? 
    unread == 0 
    end 

end 

class NotificationsController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    @notification = current_user.notification 
    @notification.unread? ? (@notification.update_attributes("unread", 0) : (redirect_to root_path)) 
    end 
end 
相關問題