Question: I have a car and user model. 

```
User.rb
has_many :cars

Car.rb
belongs_to :user

```

I would like to validate model field in the car model only if its user has `mdk_id` not nil.

This is how I create car model, 

```
user = User.where(mdk_id: b["companyid"]).first

car = user.cars.build 

```

Then in `Car.rb` model, I would like to validate `model` field.

I tried;

```
  validates :model if self.user.mdk_id != nil

```

But it gives error;

```
undefined method `user' for #<Class:0x007f973a321a58>

```

How can I reference that ?

Answer: 
You can pass a proc to the if option like this:

```
validates :model, presence: true, if: proc { |car| car.user.mdk_id? }

```

(I assumed you need to validate presence of the field, you can change the validation if you need).

Please, check out the [rails guides](http://guides.rubyonrails.org/active_record_validations.html#validation-helpers#using-a-proc-with-if-and-unless) on this topic.
You can do like these in Car.rb

```
validate :validate_user, on: [:create, :update]

def validate_user
  if self.user.mdk_id == nil
    #display error message here
    #such as User's mdk_id cannot be null etc.
  end
end

```