validates presence of foreign key fails in nested form

I’m using accepts_nested_attributes as follows:

class Timesheet < ActiveRecord::Base

attr_accessible :status, :user_id, :start_date, :end_date, :activities_attributes

has_many :activities, dependent: :destroy

has_many :time_entries, through: :activities

accepts_nested_attributes_for :activities, allow_destroy: true

end

class Activity < ActiveRecord::Base

attr_accessible :task_id, :timesheet_id, :time_entries_attributes

validates :task_id, presence: true, uniqueness: { scope: ‘timesheet_id’}

belongs_to :timesheet

belongs_to :task

has_many :time_entries, order: :workdate, dependent: :destroy

accepts_nested_attributes_for :time_entries, allow_destroy: true, reject_if: proc { |a| a[:worktime].blank? }

end

As you see, I didn’t define any validation for timesheet_id presence in Activity model. It works fine in the browser, but it is still possible to create an activity without timesheet_id assigned.

If I add:

validates :timesheet_id, presence: true

to the Activity model, I can’t any more create a timesheet via browser. Any idea ?

Regards

Found the way to do that by using ‘inverse_of’ option (see below):