Refer to belongs_to from within Model

This may be a common mistake, but I have no idea how to search for it.

I have users that input records that can be either active or inactive. I want to cap the number of active records per user at 10. I do validations within the entry model, but I don’t know how to access the user’s current records from within the entry model.

class Entry < ApplicationRecord
  belongs_to :user

  validate :not_too_many_active_records

  def not_too_many_records
    <Something>.where(active: true).count < 10
  end
end

Much Thanks!!

validate :not_too_many_records, on: [:create]

scope :active, -> { where(active: true) }

def not_too_many_records
  user.entries.active.count < 10
end

Thank you! But that does not work for me :confused:

I dropped a debugger in the not_too_many_records function, and user.entries.active.count correctly returns the number of active records (16 in my test case), but the validation still passes? The record is created even though 16 is not less than 10

Sorry, I forgot that custom validation methods have to add to the errors collection when invalid, not just return false.

def not_too_many_records
  if user.entries.active.count >= 10
    errors.add("too many active entries")
  end
end
1 Like

Works great! thanks much

The rails guides are pretty good. Definitely give them a read Active Record Validations — Ruby on Rails Guides

1 Like