Came across this post & it says referential integrity handled by the DB is not the Rails way at all.
But consider this:
class User < ActiveRecord::Base
belongs_to :department
end
class Department < ActiveRecord::Base
has_many :users
end
#User Model
id: integer, name: string,department_id: integer
#Department Model
id: integer, name: string
Here I need to create a new user & enforce following rules
- User should be assigned to a department
- the
users.department_id
should matchdepartments.id
- if
users.department_id
doesn't not match withdepartments.id
, the record should NOT be created & raise an error.
Now, how to I accomplish this in rails way? Or Adding foreign key by dropping raw SQL in a migration is only way to go?