vendredi 14 juillet 2017

before_destroy check if attribute for related model is given (version control)

i have a model which has_many relation to a version model. Any action on the parent model need to be tracked. At the form for delete i have added a nested form to enter a ticket number which will be added to the versions. How could i check in the model validations if the ticket is given? I will write the version before the destroy on the model is called.

# model.rb
class Model < ActiveRecord::Base
      has_many    :versions,
                  :as => :version_object
end

# models_controller.rb
def destroy                                             
    @model = Model.find(params[:id])                 
    self.write_versions('Destroy')                        
    @Model.destroy                                     

    respond_to do |format|                                
      ...
    end                                                   
  end

# delete.html.erb
<%= form_for [@model.parent_object, @model], :html => { :class => 'form-horizontal' }, :method => :delete
    do |f| %>
      <div class="form-actions">
        <%= f.fields_for :versions, @model.versions.build do |v| %>
          <%= v.text_field :ticket, {:class => 'text_field', :placeholder => 'Ticket Nummer'}%>
        <% end %>
        <%= f.submit 'Delete Model', :class => 'btn btn-danger' %>
        <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                    :back, :class => 'btn' %>
      </div>
    <% end %>

I already tried to implement a before_destroy method to check if a version with the 'Destroy' action is written but this won't work because the key fields to identify the certain action could be exist more than one time. The versions are incremental and can be rolled back step by step to get an older version and my model could have more than one relation identifier at the lifetime of his parent.

An solution would be to check the existence of the ticket at the controller through the params, but validations should be at the model.

I don't want to use a versioning gem.

Anybody a hint how to implement such a validation?

Aucun commentaire:

Enregistrer un commentaire