S
S
Sworg2017-06-10 23:18:40
Ruby on Rails
Sworg, 2017-06-10 23:18:40

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

1 answer(s)
D
Dmitri Sinitsa, 2017-06-11
@Sworg

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 question

Ask a Question

731 491 924 answers to any question