# Validates\_presence\_of foreign key

**URL:** <https://www.ruby-forum.com/t/validates-presence-of-foreign-key/92954>\
**Category:** Rails\
**Created:** [April 26, 2007, 12:16am UTC](https://www.ruby-forum.com/t/validates-presence-of-foreign-key/92954 "2007-04-26T00:16:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/9f8e36/32.png) [@kim](https://www.ruby-forum.com/u/kim)\
**Post date:** [April 26, 2007, 12:16am UTC](https://www.ruby-forum.com/t/validates-presence-of-foreign-key/92954/1 "2007-04-26T00:16:37Z")

</div>

Does validates\_presence\_of work for foreign keys?

I have a Service model the belongs to Agent I then have  
validates\_presence\_of :title, :locator, :agent\_id, :user\_id  
in my model.

But I can create Services with out choosing an agent and it saves and  
validates just find. Why??? Why doesn’t the validates\_presence\_of  
prohibit the service from being created without an agent?

Here is my relevant create code:  
unless params[:agent]||params[:agent] == “-- Select an Agent --” #  
check if an agent was choosing  
agent = Agent.find(params[:agent]) #find the agent  
@service.agent\_id = agent.id #assign the agent to the service  
end  
if @service.save  
#do stuff

How do I make sure that the service has an agent before it is created?

Thanks in advance, K

---

<div class="post-metadata">

**Author:** ![kim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/9f8e36/32.png) [@kim](https://www.ruby-forum.com/u/kim)\
**Post date:** [April 26, 2007, 1:35am UTC](https://www.ruby-forum.com/t/validates-presence-of-foreign-key/92954/2 "2007-04-26T01:35:42Z")

</div>

Bumpty Bump

---

<div class="post-metadata">

**Author:** ![kim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/9f8e36/32.png) [@kim](https://www.ruby-forum.com/u/kim)\
**Post date:** [April 26, 2007, 2:05am UTC](https://www.ruby-forum.com/t/validates-presence-of-foreign-key/92954/3 "2007-04-26T02:05:43Z")

</div>

Try validating against the the association rather than the foreign  
key.

class Service \< ActiveRecord::Base  
belongs\_to :agent  
validates\_presence\_of :agent  
end
