Reputation: 5905
I have a project model:
class Project < ApplicationRecord
has_many :site_visits, inverse_of: :project, dependent: :destroy
accepts_nested_attributes_for :site_visits, allow_destroy: true, reject_if: :all_blank
before_save: :convert_site_visit_dates
def convert_site_visit_dates
begin
if self.site_visits_attributes.present?
self.site_visits_attributes.each do |site_visit|
site_visit[1]['visit_date'] = convert_date(site_visit[1]['visit_date']) if site_visit[1]['visit_date'].present?
site_visit[1]['_destroy'] = true if site_visit[1]['_destroy'] == "1"
end
end
rescue StandardError
nil
end
end
end
I have site_visit model: (columns - visit_date
)
class SiteVisit < ApplicationRecord
belongs_to :project
end
Before saving the site_visits in any particular project through cocoon gem I need to change the value of the site_visits_attributes
using a callback. In my project model you can see I've defined a callback to change the visit_date
column of site_visit
table. But the value is not changing. Thus, in the database null values are being saved.
Any idea what's wrong?
Upvotes: 0
Views: 652
Reputation: 2169
site_visits_attributes
is not a method on the Project object. If you remove rescue StandardError
you'll catch this issue.
It is probably a better idea to modify the data in a before_filter
in your controller. Or alternatively, you could modify the data on before_save
on the SiteVisit objects.
Upvotes: 1