Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Record < ApplicationRecord
- has_many :record_associations
- has_many :linked_records, through: :record_associations
- has_many :references, foreign_key: :linked_record_id, class_name: 'Record'
- has_many :linking_records, through: :references, source: :record
- ...
- end
- class RecordAssociation < ApplicationRecord
- belongs_to :record
- belongs_to :linked_record, :class_name => 'Record'
- validates :label, presence: true
- ...
- end
- def create
- # Record associations must be added separately due to the through model, and so are extracted first for separate
- # processing once the record has been created.
- associations = record_params.extract! :record_associations
- @record = Record.new(record_params.except :record_associations)
- @record.add_associations(associations)
- if @record.save
- render json: @record, status: :created
- else
- render json: @record.errors, status: :unprocessable_entity
- end
- end
- def add_associations(associations)
- return if associations.empty? or associations.nil?
- associations[:record_associations].each do |assoc|
- new_association = RecordAssociation.new(
- record: self,
- linked_record: Record.find(assoc[:linked_record_id]),
- label: assoc[:label],
- )
- record_associations << new_association
- end
- end
- {"record_associations":["is invalid"]}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement