[英]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_for
和validates_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.