Answer the question
In order to leave comments, you need to log in
How to make a form object to update a post, not just create one?
There is a form object to create an entry and the necessary associations. How to competently extend the class so that it provides the correct update of the data, and not just the creation?
module Company
class JobForm
include ActiveModel::Model
attr_accessor :title, :body, :city, :start_date, :attachments,
:requirements, :company
attr_reader :object
validates :title, :body, :start_date, :city, presence: true
def save
persist! if valid?
end
private
def persist!
ActiveRecord::Base.transaction do
save_job
save_attachments
save_requirements
end
object
end
def save_job
@object = company.jobs.create(
# attributes.. ..)
end
def save_attachments
return unless attachments&.present?
attachments.each do |attacment_attributes|
object.attachments.create(attacment_attributes)
end
end
def save_requirements
return unless requirements&.present?
object.requirements.destroy_all
requirements.each do |requirement_attributes|
object.requirements.create(requirement_attributes)
end
end
end
end
Answer the question
In order to leave comments, you need to log in
And how to update? Which entities should be updatable?
By the way, you have incorrectly implemented transactionality - the "create" method (without an exclamation point) does not throw an exception, and therefore the transaction will not be rolled back in case of an error.
Also, an ampersand for safe navigation is not needed when checking requirements for existence.
attr_accessor is also already dead like :D
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question