简体   繁体   中英

Rails: Access parent model attributes in nested model validations

I have Project model that has_many tasks . The Project model accepts_nested_attributes_for and validates_associated tasks .

In my @project form I'm submitting multiple tasks for each project in a single submit. I wish to run validations on my nested tasks based on the project type. As follows:

Task model:

  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

undefined method cat for nil:NilClass

Apparently the project_id attribute has not yet been set in the Task model (?).

How do I access a parent Project model attributes in my nested Task model during validation?

You might need to use inverse_of for this. By setting inverse_of to your models, Rails will use the same record objects in memory when accessing the associated records. Not entirely sure if this will work, but you could try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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