加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails accepted_nested_attributes_for验证时,

发布时间:2020-12-16 21:58:35 所属栏目:百科 来源:网络整理
导读:验证时,我试图访问我的子模型中的父模型.我在has_one上发现了一个关于反向属性的东西,但是我的Rails 2.3.5不能识别它,所以它一直没有被发布.我不知道这是否正是我需要的. 我想基于父属性有条件地验证孩子.我的父模型已经创建.如果在父级更新_属性时尚未创建
验证时,我试图访问我的子模型中的父模型.我在has_one上发现了一个关于反向属性的东西,但是我的Rails 2.3.5不能识别它,所以它一直没有被发布.我不知道这是否正是我需要的.

我想基于父属性有条件地验证孩子.我的父模型已经创建.如果在父级更新_属性时尚未创建该子项,那么该父对象无法访问.我想知道我如何访问这个父母.这应该很容易,像parent.build_child这样的东西设置子模型的parent_id,为什么在为child_nested_attributes_for构建孩子时不会这样做?

例如:

class Parent < AR
  has_one :child
  accepts_nested_attributes_for :child
end
class Child < AR
  belongs_to :parent
  validates_presence_of :name,:if => :some_method

  def some_method
    return self.parent.some_condition   # => undefined method `some_condition' for nil:NilClass
  end
end

我的表格是标准的:

<% form_for @parent do |f| %>
  <% f.fields_for :child do |c| %>
    <%= c.name %>
  <% end %>
<% end %>

使用更新方法

def update
  @parent = Parent.find(params[:id])
  @parent.update_attributes(params[:parent])   # => this is where my child validations take place
end

解决方法

我有一个类似的问题: Ruby on Rails – nested attributes: How do I access the parent model from child model

这是我最终解决的问题通过设置父回调

class Parent < AR
  has_one :child,:before_add => :set_nest
  accepts_nested_attributes_for :child

private
  def set_nest(child)
    child.parent ||= self
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读