在Rails 5中,给出了这两个模型:
class Solution < ApplicationRecord
has_many :tasks, -> { order(name: :asc) }
end
class Task < ApplicationRecord
belongs_to :solution
end
此代码将失败并显示ActiveRecord::RecordInvalid: Validation failed: Tasks is invalid
:
solution = Solution.new(name: "My Solution", tasks: [
Task.new(name: "My Task")
])
solution.save!
这是由于任务的solution
为nil
:
(byebug) pp solution.tasks[0].errors.messages
{:solution=>["must exist"]}
但是,从has_many
子句中删除订单(只到has_many :tasks
)时,它可以正常工作:
(byebug) pp solution.tasks[0].solution == nil
false
这是预期的吗?
示例项目(查看最后两次提交):https://github.com/hannesstruss/test_order_validation
答案 0 :(得分:0)
使用inverse_of
修复了它:
has_many :tasks, -> { order(name: :asc) }, inverse_of: :solution
和
belongs_to :problem, inverse_of: :tasks