2013-03-25 80 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 
相关问题