![](/img/trans.png)
[英]Rails 3.0.11 : attributes= on a parent model will call validations on nested models
[英]Rails: Access parent model attributes in nested model validations
我有has_many
tasks
Project
模型。 Project
模型accepts_nested_attributes_for
和validates_associated
tasks
。
在我的@project
表單中,我要在一個提交中為每個project
提交多個tasks
。 我希望根據項目類型對嵌套tasks
進行驗證。 如下:
Task
模型:
with_options if: :special_project? do |task|
task.validate :is_possible
end
def special_project?
project.cat == 'special'
end
不幸的是,Rails給了我一個NilClass
錯誤
undefined method cat for nil:NilClass
顯然,尚未在Task
模型(?)中設置project_id
屬性。
在驗證期間,如何訪問嵌套Task
模型中的父Project
模型屬性?
您可能需要為此使用inverse_of 。 通過為模型設置inverse_of
,Rails在訪問關聯的記錄時將在內存中使用相同的記錄對象。 不能完全確定是否可以,但是您可以嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.