如何检查会员是否至少有一个活跃会员?

ni65a41a  于 2022-10-15  发布在  Ruby
关注(0)|答案(1)|浏览(166)

我一直在想办法解决我的问题,但没有结果。我正在试着检查进入的会员是否有活跃的会员资格。

class Entry < ApplicationRecord
  belongs_to :member
  before_create :status

  def status
    member = Member.find(member_id)
    if member.has_active_membership
      return true
    else
      return false
    end
  end
end
class Member < ApplicationRecord
    has_many :memberships
    has_many :passes, through: :memberships

    def has_active_membership
        self.memberships.active?
    end
end
class Membership < ApplicationRecord
  belongs_to :member
  belongs_to :pass

  def active?
    if (self.valid_until >= Date.today)
      return true
    else
      return false
    end
  end
end
undefined method `active?' for #<ActiveRecord::Associations::CollectionProxy [#<Membership id: 1, name: "XD", valid_from: "2022-10-01", valid_until: "2022-10-31", member_id: 2, pass_id: 2, created_at: "2022-10-01 19:41:43.186045000 +0000", updated_at: "2022-10-01 19:41:43.186045000 +0000">]>
Did you mean?  acts_like? //error for member.rb has_active_membership

我正在努力检查会员是否至少有一个活跃的会员。谢谢你的帮助

fsi0uk1n

fsi0uk1n1#

问题是您调用的是集合上的active?,而不是单个成员资格
考虑到active?的实现方式,它不是一个作用域,您应该这样做

def has_active_membership
  memberships.any?(&:active?)
end

另一种方法是将活动实现为作用域

scope :active, -> { where('valid_until >= ?', Date.today) }

然后

def has_active_membership
  memberships.active.exists?
end

相关问题