Codebeerstartups

Every Dog has one Blog

Use Belongs_to With Presence Validator

Assume we have two models: User and Image. User has one image and image belongs to user. The code below:

1
2
3
4
5
6
7
class User < ActiveRecord::Base
  has_one :image
end

class Image < ActiveRecord::Base
  belongs_to :user
end

Now we want to add validation for image to check if user is there or not.

1
2
3
4
class Image < ActiveRecord::Base
  belongs_to :user
  validates :user, :presence => true
end

So by adding just one line whenever you are trying to save image object, it will fire a query with respect to the user_id to check weather that user exists or not. In case user doesn’t exits “image.save” with return an error.

Happy Hacking :)

Comments