2013-03-25 2 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

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

@ notification.unread ==-не изменит значение атрибута. :)

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 
Смежные вопросы