2015-12-14 78 views
0

我有这令人困惑的轨道错误。如果任何人都可以解释这意味着什么比将有助于困惑的轨道错误

认购#unseen_count委托给notification_count.unseen_count,但NOTIFICATION_COUNT是零:#

这里是订阅模式

class Subscription < ActiveRecord::Base 
    belongs_to :user 
    has_one :notification_count, :dependent => :destroy 
    validates :user_id, :presence => true 
    validates :subscribe_id, :presence => true 
    after_create :notification_unseen_count 
    delegate :unseen_count, to: :notification_count, allow_nil: true 

    # Add the new subscription of the user with the provider 
    def self.add_subscription(user, subscribe) 
    user.subscriptions.where(:subscribe_id => subscribe.id).first_or_create 
    end 

    # Remove the subscription of the user with the provider 
    def self.remove_subscription(user, subscribe) 
    user.subscriptions.where(:subscribe_id => subscribe.id).destroy_all 
    end 

    # Get the provider with the subscription 
    def subscribe 
    User.find(subscribe_id) 
    end 

    # Mark as read the notification count as soon as the users goes to providers feed 
    def mark_as_read 
    notification_count.update(:unseen_count => 0) 
    end 

    private 

    # As soon as the new subscription will create the notification count will be added fot the subscriber 
    def notification_unseen_count 
    NotificationCount.create(:subscription_id => self.id) 
    end 
end 

这里是通知型号:

class NotificationCount < ActiveRecord::Base 
    belongs_to :subscription 
    belongs_to :premium_subscription 
    validates :subscription_id, :presence => true 
    validates :premium_subscription_id, :presence => true 

    # Update the notification count when the new content lived for all the subscribed users 
    def self.update_notification_count subscriptions 
    subscriptions.each{ |subscription| subscription.notification_count.update(:unseen_count => subscription.unseen_count + 1)} 

end 

编辑:几个小时后,无济于事。如果有人对此问题有任何煽动,请告诉我。

回答

0

delegate操作可以将包含对象的方法,就好像它是物体本身的方法。

所以在这种情况下,而不是写subscription.notification_count.unseen_count可以使用subscription.unseen_count和Rails会自动调用,通过对相关notification_count为您unseen_count方法。

但是,如果订阅没有关联的notification_count,您将遇到您看到的错误。

在你的代码after_create :notification_unseen_count意在创建Subscription所以看起来你可能只是有一些无效数据在数据库中创建的每个Subscription一个NotificationCount

0

您可以在代表团上使用allow_nil: true以防止出现此错误。 这是因为你对你的Subscription模型委托unseen_countnil

Docs for delegate method

+0

有没有办法让它不零......对不起...我仍然在学习如何工作。非常感谢您的帮助:) – Jakxna360

+0

您需要显示两种型号的代码才能进一步帮助 –

+0

我添加了这些型号。再次感谢您的帮助:) – Jakxna360