I am learning how validates_presence_of works. Suppose I have two models
class Project < ActiveRecord::Base [...] has_many :roles end
and
class Role < ActiveRecord::Base validates_presence_of :name, :project belongs_to :project end
I want the role to always belong to an existing project, but I just learned from this example that this can lead to invalid (lost) roles stored in db. So the right way to do this is to insert validates_presence_of :project_id in my role model and it seems to work even if I think it semantically makes sense to check for a project instead of a project identifier.
In addition, I thought that I could put an invalid id (for a non-existing project) if I just check for the presence of project_id, since by default AR does not add integrity checks to the migration, and even if I add them manually some databases do not support them (t .e. MySQL with MyISAM or sqlite). This example proves that
# with validates_presence_of :name, :project, :project_id in the role class Role.create!(:name => 'foo', :project_id => 1334, :project => Project.new) AREL (0.4ms) INSERT INTO "roles" ("name", "project_id") VALUES ('foo', NULL) +----+------+------------+ | id | name | project_id | +----+------+------------+ | 7 | foo | | +----+------+------------+
Of course, I will not write such code, but I want to prevent such incorrect data in the database.
I wonder how to ensure that the role ALWAYS has a (real and saved) project.
I found a validates_existence gem, but I prefer not to add a gem to my project if it is strictly necessary.
Any thought on this?
Update
validates_presence_of :project and adding :null => false for the project_id column in the wrap seems like a cleaner solution.