【问题标题】:Nested create via JSON - validation on the nested model通过 JSON 进行嵌套创建 - 对嵌套模型进行验证
【发布时间】:2013-04-11 05:41:56
【问题描述】:

我有两个简单的模型:

class Idea << ActiveRecord::Base
  has_many :tasks

  # for nesting....
  accepts_nested_attributes_for for :tasks
  attribute_accessible :tasks_attributes
end

class Task << ActiveRecord::Base
  belongs_to :idea
  validates_presence_of :idea # this line is causing pain
end

我发送以下 JSON 来创建我的 IdeasController:

{
    "description":"Test test test",
    "tasks":[{"description":"test test test"}]
}

... 我得到了验证错误。一旦我删除验证,一切都会好起来的!

有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-3


    【解决方案1】:

    定义反向关联会有所帮助:

    class Idea << ActiveRecord::Base
      has_many :tasks, inverse_of: :idea # here...
      accepts_nested_attributes_for :tasks
      attribute_accessible :tasks_attributes
    end
    
    class Task << ActiveRecord::Base
      belongs_to :idea, inverse_of: :tasks # ... and here
      validates_presence_of :idea 
    end
    

    验证失败的原因是在此修复之前关联是单向的:当您尝试到达任务的idea 时,而不是使用用于从它的想法到达任务的关联代理,它会创建另一个关联不知道这个想法的存在的代理(对不起,这有点难以解释)。

    另外,请务必使用 validates_presence_of :idea 而不是 validates_presence_of :idea_id。此外,您应该在 json 中使用 tasks_attributes 而不仅仅是 tasks

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 2015-03-31
      • 1970-01-01
      • 2016-02-19
      • 2016-04-29
      • 2012-12-12
      相关资源
      最近更新 更多