Advertisement
Guest User

Untitled

a guest
Jun 15th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. class Record < ApplicationRecord
  2. has_many :record_associations
  3. has_many :linked_records, through: :record_associations
  4. has_many :references, foreign_key: :linked_record_id, class_name: 'Record'
  5. has_many :linking_records, through: :references, source: :record
  6. ...
  7. end
  8.  
  9. class RecordAssociation < ApplicationRecord
  10. belongs_to :record
  11. belongs_to :linked_record, :class_name => 'Record'
  12.  
  13. validates :label, presence: true
  14. ...
  15. end
  16.  
  17. def create
  18. # Record associations must be added separately due to the through model, and so are extracted first for separate
  19. # processing once the record has been created.
  20. associations = record_params.extract! :record_associations
  21. @record = Record.new(record_params.except :record_associations)
  22. @record.add_associations(associations)
  23. if @record.save
  24. render json: @record, status: :created
  25. else
  26. render json: @record.errors, status: :unprocessable_entity
  27. end
  28.  
  29. end
  30.  
  31. def add_associations(associations)
  32. return if associations.empty? or associations.nil?
  33. associations[:record_associations].each do |assoc|
  34. new_association = RecordAssociation.new(
  35. record: self,
  36. linked_record: Record.find(assoc[:linked_record_id]),
  37. label: assoc[:label],
  38. )
  39. record_associations << new_association
  40. end
  41. end
  42.  
  43. {"record_associations":["is invalid"]}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement