Use belongs_to with presence validator

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

  class User < ActiveRecord::Base
    has_one :image
  end

  class Image < ActiveRecord::Base
    belongs_to :user
  end

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

  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 whether that user exists or not. In case the user doesn’t exit “image.save” with return an error.

Happy Hacking :)