2014-07-14 43 views
1

我有一个NoMethodError undefined method `where' for <Subscription:0x000001083aee00>。它指向我的用户型号subscription.where(cancelled: nil).exists?NoMethodError undefined method'where'

在视图中,我试图设置if语句,以便我可以向订阅表中的取消状态不为零的用户显示选择的内容。

用户模式:

has_one :subscription 

    def paid? 
     subscription.where(cancelled: nil).exists? 
    end 

has_one关系是从一开始就对应用程序的其他部分。当我加入belongs_to关系,我得到的错误undefined method `where' for nil:NilClass

+0

您使用的是哪种版本的导轨? – dax

+0

@dax我有Rails 4 – xps15z

回答

3

如果订阅用户的属性,如果是取消订阅,你可以做的布尔属性...

def paid? 
    !subscription.cancelled? if subscription 
end 

where只能如果使用的话用户和订阅之间存在一对多关系,或者它可以在订阅类本身上使用。

subscription.cancelled?如果它被取消,将返回true如果它没有以“not”符号作为前缀,如!subscription.cancelled?将返回true,如果它没有被取消。

尾随... if subscription的原因处理用户不存在订阅的情况,在这种情况下将返回false(nil)。

+0

感谢您的提示! – xps15z

相关问题