Validates_presence_of foreign key


#1

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


#2

Bumpty Bump


#3

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

class Service < ActiveRecord::Base
belongs_to :agent
validates_presence_of :agent
end