A report_template
has_many
report_template_columns
, which each have a
name
and an index
attribute.
class ReportTemplateColumn < ApplicationRecord
belongs_to :report_template
validates :name, presence: true
end
class ReportTemplate < ApplicationRecord
has_many :report_template_columns, -> { order(index: :asc) }, dependent: :destroy
accepts_nested_attributes_for :report_template_columns, allow_destroy: true
end
The report_template_columns
need to be ordered by the index column. I'm applying this with a scope on the has_many
association, however doing so causes the following error:
> ReportTemplate.create!(report_template_columns: [ReportTemplateColumn.new(name: 'id', index: '1')])
ActiveRecord::RecordInvalid: Validation failed: Report template columns report template must exist
from /usr/local/bundle/gems/activerecord-5.1.4/lib/active_record/validations.rb:78:in `raise_validation_error'
If I remove the scope the same command succeeds.
If I replace the order
scope with where
scope that command fails in the same way, so it seems to be the presence of the scope rather than the use of order
specifically.
How can I apply a scope to the has_many
without breaking the nested creation?
defualt_scope
. It may seem convient but will make things very difficult if you don't want the scope applied later. weblog.jamisbuck.org/2015/9/19/default-scopes-anti-pattern.html – Aldus