ruby-on-rails - 嵌套属性无法使用新父级创建子级

标签 ruby-on-rails ruby-on-rails-3 nested-attributes

我有两个模型:

class Shift < ActiveRecord::Base
  attr_accessible :ranges_attributes
  has_many :ranges
  accepts_nested_attributes_for :ranges, allow_destroy: true
end

class Range < ActiveRecord::Base
  belongs_to :shift
  validates :shift, presence: true
end

当我想在我的 Controller 中创建一个具有我得到的范围的类次时:

Shift.create! params[:shift]
#ActiveRecord::RecordInvalid Exception: Validation failed: Shift ranges shift can't be blank

如果我从 Range 模型中删除 validates :shift, Presence: true ,效果会非常好。我能够和他的 children 一起创造新的转变。 ActiveRecord 为我做到了这一点。

问题是:为什么我需要删除该验证才能使其正常工作?

最佳答案

像这样验证 parent 在场的事情是时机!!实际上,Shift 尚未保存,因此在尝试创建嵌套范围时,它不会在数据库中找到父级Shift

我找到了这个解决方法 here

class Shift < ActiveRecord::Base
  attr_accessible :ranges_attributes
  has_many :ranges, :inverse_of => :shift
  accepts_nested_attributes_for :ranges, allow_destroy: true
end

我引用同一来源(稍作修改):

With this option rails won't try to get parent from database when child is validated. The parent will be got from memory. If you don't familiar with this option I strongly recommend you to read an official rails guide

关于ruby-on-rails - 嵌套属性无法使用新父级创建子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991443/

相关文章:

ruby-on-rails - Rails SQLite Dev 和 Test 数据库是相同的。为什么?

ruby-on-rails - Turbo-rails 不同范围的部分广播更新

ruby-on-rails-3 - 如何使用 Capybara 获取、显示、发布、放入 Controller 测试?

sql - rails query hstore where key IS NOT something 或不存在

ruby-on-rails - 创建记录时出错 : nil object instead of array?

ruby-on-rails-3 - 通过 link_to 合并嵌套参数

javascript - Jquery 在控制台中有效,但在 Rails 4 application.js 文件中无效

ruby-on-rails - 无法连接到chromedriver

java - HTTP-POST 图像到 Ruby on Rails 应用程序

ruby-on-rails - first_or_create 通过电子邮件然后保存嵌套模型