Skip to content

Instantly share code, notes, and snippets.

@ornerymoose
Last active November 24, 2017 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ornerymoose/863d6b0ccd1e036792d9af229b6be7c8 to your computer and use it in GitHub Desktop.
Save ornerymoose/863d6b0ccd1e036792d9af229b6be7c8 to your computer and use it in GitHub Desktop.
Given the custom validation in relationship.rb, if I try to update an outage with a child that is already associated to a different outage, it gives me a validation error. It's trying to create a new relationship, not update one. If I pass the on: :create to the custom validation, that won't work since it's trying to create a new relationship on…
class Child < ApplicationRecord
has_many :relationships
has_many :outages, through: :relationships
end
class Outage < ApplicationRecord
has_many :relationships
has_many :children, through: :relationships
def self.destroy_current_relationship(outage_id, child_id)
Relationship.where(outage_id: outage_id).where(child_id: child_id).destroy_all
end
end
class Relationship < ApplicationRecord
belongs_to :child
belongs_to :outage
validate :ensure_one_relationship
def ensure_one_relationship
if Relationship.where(child_id: self.child_id).present?
errors.add(:base, "A trouble ticket can only be associated with one outage ticket.")
end
end
end
<%= form_for(@outage) do |f| %>
<p>
<div class="form-group">
<%= collection_check_boxes(:outage, :child_ids, Child.all, :id, :omnia_trouble_ticket) do |b| %>
<div class="col-xs-12">
<div class="row">
<%= b.label(class: "check_box") do %>
<%= b.check_box(class: "check_box") %><%= b.object.omnia_trouble_ticket %>
<% end %>
</div>
</div>
<% end %>
</div>
</p>
<%= f.submit("Update Outage", class: "btn btn-default") %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment