Q:

Adding order to a relation makes relation saving fail

In Rails 5, given these two models:
class Solution < ApplicationRecord
  has_many :tasks, -> { order(name: :asc) }
end

class Task < ApplicationRecord
  belongs_to :solution
end

This code will fail with ActiveRecord::RecordInvalid: Validation failed: Tasks is invalid:
solution = Solution.new(name: "My Solution", tasks: [
  Task.new(name: "My Task")
])

solution.save!

This is due to the task's solution being nil:
(byebug) pp solution.tasks[0].errors.messages
{:solution=>["must exist"]}

However, when removing the order from the has_many clause (into just has_many :tasks), it works fine:
(byebug) pp solution.tasks[0].solution == nil
false

Is this expected?
Example project (look at the last two commits): https://github.com/hannesstruss/test_order_validation

A:

Using inverse_of fixes it:
has_many :tasks, -> { order(name: :asc) }, inverse_of: :solution

and
belongs_to :problem, inverse_of: :tasks

