Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Validating existence of an association

I have a Category and a Post model, with each Post belonging to a Category. Before creating or updating a post, I need to check that the category selected exists. What's the best way to validate this information?

At the moment, I'm doing a find in the controller to ensure that the category exists. Is it possible to put these kinds of validations in the model?

like image 778
Homar Avatar asked Aug 26 '09 03:08

Homar


People also ask

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is the difference between validate and validates in rails?

validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean. That test fails.

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".


1 Answers

http://blog.hasmanythrough.com/2007/7/14/validate-your-existence

class Post < ActiveRecord::Base
  belongs_to :category
  validates_presence_of :category 
end

-OR-

class Post < ActiveRecord::Base
  belongs_to :category
  validates :category, presence: true
end

Rails versions prior to 3.2:

class Post < ActiveRecord::Base
  belongs_to :category
  validates_existence_of :category 
end
like image 75
Terry G Lorber Avatar answered Sep 23 '22 20:09

Terry G Lorber