Reputation: 1
I am trying to create a record in ClientUserEmailPreference when an email record is newly created. I tried after_create
to create a new record whenever new email record is created. But, When I try to create a new email record, it shows ArgumentError: You need to supply at least one validation
The following is my email model.
class Email < ApplicationRecord
belongs_to :email_type
belongs_to :email_preference_section
has_many :client_user_email_preferences
validates :name, allow_blank: false, presence: true
validates :email_type_id, allow_blank: false, presence: true
validates :email_preference_section_id, allow_blank: true
validates :position, allow_blank: false, presence: true
after_create :set_default_to_client_users
def set_default_to_client_users
new_preference = ClientUserEmailPreference.new
new_preference.client_user_id = that_client_user.id
new_preference.email_id = self.id
new_preference.enabled = true
if self.email_type_id != 1
new_preference.frequency = "every week"
new_preference.day_of_the_week = 1
end
new_preference.save
end
end
I don't know how to effectively create a row in ClientUserEmailPreference whenever a new email is created
Upvotes: 0
Views: 257
Reputation: 17834
The error is probably at this line
validates :email_preference_section, allow_blank: true
Since it's an association, if you want it be optional remove the above validation and then do this instead
belongs_to :email_preference_section, optional: true
Also, you don't need this line too since it is enabled by default for foreign keys
validates :email_type_id, allow_blank: false, presence: true
Give it a try!
Upvotes: 1