Reputation: 87
I have two models Building and Listing. The Listing model belongs to Building. We have been trying to restrict the number of records that can be created in Listing depending on the number of active Listing records at a given time e.g. Listing.active.count can never be more than X. We tried to use a validation where if an integer column in Building were used as the limit, but it was not working and getting the following error,
undefined method `>=' for #<Array:0x007f05ec4db388>
Listing.rb
Class Listing < Application Record
validates :validate_listing_count, on :create
private
def validate_listing_count
errors.add(:base, "You have too many active listings, please destroy a listing or contact your Account Manager if you need more listings") unless too_many_siblings?
end
def active_siblings
building.listings.where(active: true)
end
def too_many_siblings?
active_siblings.select { |sib| sib.id != id } >= (building.listing_limit - 1)
end
end
Upvotes: 0
Views: 50
Reputation: 6036
active_siblings.select
returns an array and you want the number of items in the array. Try this:
def too_many_siblings?
active_siblings.select { |sib| sib.id != id }.count >= (building.listing_limit - 1)
end
This was not part of the question, by you may want to change unless
to if
in validate_listing_count
. I think it makes more logical sense base on your description of the problem.
Upvotes: 1