Validates_presence_of foreign key


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 = #assign the agent to the service
#do stuff

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

Thanks in advance, K


Bumpty Bump


Try validating against the the association rather than the foreign

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