Home > Blockchain >  Count number of records in has_one relation
Count number of records in has_one relation

Time:10-13

I have a model Car which have a has_one relation with another model Owner. I am writing a method to validate that a Car has only one Owner but the count method is not working.

I was trying something like

if car.owner.present? && car.owner.count > 1
  errors << A car can only have one owner
end

But I am getting the below error

NoMethodError Exception: undefined method 'count'

I figured that the count method doesn't work in a has_one relationship but is there any other way to count or validate that it has only one record ? or is there any better way to write the test unit that I am trying to ?

CodePudding user response:

car.owner, as defined by has_one, returns either an instance of User or nil - but, not the relationship. The assumption is that there always should be just one record, however it is not enforced.

If you really want to enforce this, you should create a unique index on owner_id column - validations tend to having some racing conditions...

  • Related