Home > Blockchain >  How to check if member has at least one active membership?
How to check if member has at least one active membership?

Time:10-13

I've been trying to find a solution for my problem but with no result. I'm trying to check if member that entered has active membership.

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

I'm struggling with checking if member has at least one active membership. Thanks for help

CodePudding user response:

the problem is that you're calling active? on a collection, not on a single membership

considering the way active? is implemented, it's not a scope, you should do something like

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

another way is implementing active as a scope

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

and then

def has_active_membership
  memberships.active.exists?
end
  • Related