开发者

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

I have a controller/model hypothetically named Pets. Pets has 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 a request comes in as an HTTP POST to http://127.0.0开发者_如何学JAVA.1/pets, I want to create an instance of Pets. The restriction here is, if the user doesn't submit at least one dog or one cat, it should fail validation. It can have both, but it can't be missing both.

How does one handle this in Ruby on Rails? Dogs don't care if cats exists and the inverse is also true. Can anyone show some example code of what the Pets model would look like to ensure that one or the other exists, or fail otherwise? Remember that dogs and cats are not attributes of the Pets model. I'm not sure how to avoid Pets from being created if its children resources are not available though.

errors.add also takes an attribute, in this case, there is no particular attribute that's failing. It's almost a 'virtual' combination that's missing. Parameters could come in the form of 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 at least one of them exists.


You're 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 cat_name or dog_name to the controller action, it may 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 some more flexibility you can use nested attributes to create new cats and dogs in your controller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜