How to handle this type of model validation in Ruby on Rails

I have a controller / model presumably named Pets. Pets have the following declarations:

belongs_to :owner
has_many :dogs
has_many :cats

      

Not the best example, but again, it demonstrates what I'm trying to solve. Now when the request comes in as an HTTP POST on http://127.0.0.1/pets

, I want to instantiate Pets. The limitation here is that if the user doesn't submit at least one dog or one cat, this should result in a verification failure. He can have both, but he cannot be absent.

How do I handle this in Ruby on Rails? Dogs don't care if cats exist and vice versa. Can anyone show some example code for what the Pets model would look like to ensure that one or the other exists or doesn't work otherwise? Remember that dogs and cats are not attributes of the Pets model. I'm not sure how to avoid pets not being created if their resources for kids are not available.

errors.add also accepts an attribute, in this case there is no specific attribute that doesn't work. This is almost a "virtual" combination that is missing. Parameters can appear as cat_name = "bob" and dog_name = "stew", based on the attribute, I should be able to create a new cat or dog, but I need to know that at least one of them exists.

+2


a source to share


1 answer


You are looking for errors.add_to_base

. This should do the trick:

class Pet < ActiveRecord::Base
  belongs_to :owner
  has_many :dogs
  has_many :cats

  validate :has_cats_or_dogs

  def has_cats_or_dogs
    if dogs.empty? and cats.empty?
      errors.add_to_base("At least one dog or cat required")
    end
  end
end

      

If you want to pass to cat_name

or dog_name

into a controller action, it might look like this:



class PetsController < ApplicationController
  # ...

  def create
    @pet = Pet.new(params[:pet])
    @pet.cats.build(:name => params[:cat_name]) if params[:cat_name]
    @pet.dogs.build(:name => params[:dog_name]) if params[:dog_name]
    if @pet.save
      # success
    else
      # (validation) failure
    end
  end
end

      

Alternatively, for more flexibility, you can use nested attributes to create new cats and dogs in your controller.

+1


a source







All Articles