简体   繁体   English

Rails:在嵌套模型验证中访问父模型属性

[英]Rails: Access parent model attributes in nested model validations

I have Project model that has_many tasks . 我有has_many tasks Project模型。 The Project model accepts_nested_attributes_for and validates_associated tasks . Project模型accepts_nested_attributes_forvalidates_associated tasks

In my @project form I'm submitting multiple tasks for each project in a single submit. 在我的@project表单中,我要在一个提交中为每个project提交多个tasks I wish to run validations on my nested tasks based on the project type. 我希望根据项目类型对嵌套tasks进行验证。 As follows: 如下:

Task model: Task模型:

  with_options if: :special_project? do |task|
    task.validate :is_possible
  end

  def special_project?
    project.cat == 'special'
  end

Unfortunately, Rails gives me a NilClass error 不幸的是,Rails给了我一个NilClass错误

undefined method cat for nil:NilClass

Apparently the project_id attribute has not yet been set in the Task model (?). 显然,尚未在Task模型(?)中设置project_id属性。

How do I access a parent Project model attributes in my nested Task model during validation? 在验证期间,如何访问嵌套Task模型中的父Project模型属性?

You might need to use inverse_of for this. 您可能需要为此使用inverse_of By setting inverse_of to your models, Rails will use the same record objects in memory when accessing the associated records. 通过为模型设置inverse_of ,Rails在访问关联的记录时将在内存中使用相同的记录对象。 Not entirely sure if this will work, but you could try. 不能完全确定是否可以,但是您可以尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM