Forum: Ruby on Rails validates_presence_of foreign key

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Kim (Guest)
on 2007-04-26 02:16
(Received via mailing list)
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
Kim (Guest)
on 2007-04-26 03:35
(Received via mailing list)
Bumpty Bump
Robert W. (Guest)
on 2007-04-26 04:05
(Received via mailing list)
Try validating against the the association rather than the foreign

class Service < ActiveRecord::Base
  belongs_to :agent
  validates_presence_of :agent
This topic is locked and can not be replied to.