Rails嵌套属性-不创建父级 [英] Rails nested attributes - does not create parent

查看:61
本文介绍了Rails嵌套属性-不创建父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

class Parent
  has_many :cars
  accepts_nested_attributes_for :cars
end

class Car
  belongs_to :parent
  validates :parent, presence: true
end

控制器代码:

def create
  parent = Parent.new
  parent.attributes = parent_params
  parent.save
end

def parent_params
  params.require(:parent).permit(:name,  cars_attributes: [:name])
end

当我尝试用Cars创建Parent时,在Cars上的验证失败,因为尚未创建Parent.通过嵌套属性创建的商品如何通过验证?

When I try to create a Parent with Cars, the validation fails on the Cars because the Parent was not created yet. How can I make it pass validations when it's being created through nested attributes?

推荐答案

基于快速搜索,您可以使用:inverse_of来克服这种情况.

Based on a quick search, you could use :inverse_of to overcome this situation.

在您的代码中:

class Parent
  has_many :cars, inverse_of: :parent
  accepts_nested_attributes_for :cars
end

class Car
  belongs_to :parent
  validates :parent, presence: true
end

(未经测试)

查看dem来源:

  1. 验证父对象的存在(滚动到该部分).
  2. 在github上发布的问题
  3. 有些帖子我没有打扰阅读,但上面提到的问题被引用了
  1. Validating presence of the parent object (scroll to that part).
  2. Issue on github
  3. Some post I didn't bother to read but is referenced on the issue above

GL& HF.

GL & HF.

这篇关于Rails嵌套属性-不创建父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆