向关系添加顺序会使关系保存失败

时间:2017-04-19 14:50:06

标签: ruby-on-rails ruby activerecord ruby-on-rails-5

在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!

这是由于任务的solutionnil

(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

1 个答案:

答案 0 :(得分:0)

使用inverse_of修复了它:

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

belongs_to :problem, inverse_of: :tasks