I have a User
model which has many roles
. Roles contains a user_id
field, which I want to validate_presence_of
The is
For anyone Googling for a solution to this problem for a has_many :through
association, as of 5/December/2013 the :inverse_of
option can't be used in conjunction with :through
(source). Instead, you can use the approach suggested by @waldyr.ar. For example, if our models are set up as follows:
class User < ActiveRecord::Base
has_many :roles
has_many :tasks, through: roles
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :task
end
class Task < ActiveRecord::Base
has_many :roles
has_many :users, through: roles
end
We can modify our Role
class as follows to validate the presence of both task
and user
before saving
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :task
before_save { validates_presence_of :user, :task }
end
Now if we create a new User
and add a couple tasks
like so:
>> u = User.new
>> 2.times { u.tasks << Task.new }
Running u.save
will save the User
and the Task
, as well as transparently build and save a new Role
whose foreign keys user_id
and task_id
are set appropriately. Validations will run for all models, and we can go on our merry way!