ruby-on-rails - Rails accepts_nested_attributes_for child 在验证时没有设置父级

标签 ruby-on-rails activerecord relationships

验证时,我试图在我的子模型中访问我的父模型。我在 has_one 上发现了一些关于反向属性的信息,但我的 Rails 2.3.5 无法识别它,所以它一定从未进入发布版。我不确定这是否正是我需要的。

我想根据父属性有条件地验证 child 。我的父模型已经创建。如果在父级上 update_attributes 时尚未创建子级,则它无权访问父级。我想知道如何访问这个父级。应该很简单,像parent.build_child这样设置子模型的parent_id,为什么在为accepts_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

最佳答案

我在 Rails 3.2 中遇到了基本相同的问题。正如问题中所建议的,添加 inverse_of家长协会的选项为我修复了它。

应用于您的示例:

class Parent < AR
  has_one :child, inverse_of: :parent
  accepts_nested_attributes_for :child
end

class Child < AR
  belongs_to :parent, inverse_of: :child
  validates_presence_of :name, :if => :some_method

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

关于ruby-on-rails - Rails accepts_nested_attributes_for child 在验证时没有设置父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226747/

相关文章:

ruby-on-rails - Ruby:修剪或替换前导数字

mysql - 防止 ActiveRecord 对小数点进行四舍五入

ios - Realm 反向关系支持使用字典值创建

php - Eloquent 具有多对多 (belongsToMany)

ruby-on-rails - rails : Calling a controller method from another controller -> NoMethodError

ruby-on-rails - 在特定日期启用资源可用性的 Ruby/Rails 方式

php - 我应该在什么基础上构建我的 alpha 平台,PHP、Ruby、Python、.NET 等?

ruby-on-rails - saved_change_to_attribute?在方法内部调用时总是返回 false

ruby-on-rails - 列错误地从 HSTORE 返回 key

ios - 使用谓词获取核心数据中 parent 的所有 child