Search code examples
ruby-on-railsmodelrestrict

Limit user to a creation of one object in has_one relation


I am trying to make that my user can't make more than one farm. In my user model, I have:

 has_one :farm

And in my farm model, I have:

belongs_to :user
validate :farm_count_within_limit, :on => :create

def farm_count_within_limit
  if self.user.farms(:reload).size > 1
    errors.add(:base, "User can only add one farm")
  end
end

But I am getting this error:

NoMethodError in FarmsController#create

undefined method `farms' for nil:NilClass

Note that before this farm_count_within_limit I was able to create as many farms as I want with my one user. Is there a better way to restrict it so user can only add one farm?


Solution

  • has_one will create a singular farm method like this

    user = User.find(1)
    user.farm
    

    There is no need to additional checking for this in Rails. However this does not enforce at the db level that there will not be a user with more than one farm. The way to prevent that is mostly by creating a unique index. Can do so in a migration.

    add_index :farms, :user_id, unique: true
    

    That will make sure there cannot be a user with more than one farm in the db.