困惑轨道错误

时间:2015-12-14 20:34:14

标签: ruby-on-rails

我有这个令人困惑的rails错误。如果有人能够解释这意味着什么比这更有帮助

订阅#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

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

2 个答案:

答案 0 :(得分:0)

您可以在委派中使用allow_nil: true来防止此错误。 这是因为您在unseen_count模型上委派了Subscription,但它是nil

Docs for delegate method

答案 1 :(得分:0)

delegate可让您使用包含对象的方法,就像它是对象本身的方法一样。

因此,在这种情况下,您可以使用subscription.notification_count.unseen_count而不是撰写subscription.unseen_count,而Rails会自动调用相关unseen_count上的notification_count方法。

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

在您的代码中,after_create :notification_unseen_count旨在为NotificationCount创建Subscription,因为您可能只有一些无效数据数据库中。