title: validating the child based on a parent attribute
body: <pre><code>class Query &lt; ActiveRecord::Base
    #relations
    has_one :r_job
    accepts_nested_attributes_for :r_job
  end
  
  class RJob &lt; ActiveRecord::Base
    belongs_to :query
    validates_presence_of :analysis_type, :if =&gt; lambda {|job| job.query.process_r_job} 
  end
  </code></pre>
  
  <p>I have a nested form for creating a query and r_job. I have a boolean field in the query object and I have to do some validations on the r_job based on the boolean in the query object.I am trying do that with the above code, but I am getting a no method error.</p>
  
  <pre><code>NoMethodError (undefined method `process_r_job' for nil:NilClass):
     app/models/r_job.rb:3:in `block in &lt;class:RJob&gt;'
     app/controllers/queries_controller.rb:9:in `create'
  </code></pre>
  
  <p>I digged in a bit and I found, <code>job.query</code> inside lambda is returning a nil object. Im kinda stuck with this. Need some help in solving this. Below is my form and controller code.</p>
  
  <pre><code># app/views/queries/new.html.haml
  =form_for @query, {:html =&gt; {:class=&gt;"form-horizontal"}}do |f|
    - if @query.errors.any?
      .alert.alert-error
        %h4.alert-heading Error(s)!
        - @query.errors.full_messages.each do |msg|
          %p= msg
  
    =render "query_form", :f =&gt; f
  
    %fieldset
      =f.fields_for :r_job do |builder|
        =render "r_job_form", :f =&gt; builder
    %button.btn.btn-primary.small Go
  
  #app/controller/queries_controller.rb
  class QueriesController &lt; ApplicationController
    def new
      @query = Query.new
      @query.build_r_job
    end
  
    def create
      @query = Query.new(params[:query])
      if @query.save
        redirect_to root_path, :notice =&gt; "Yay!! Your query is running. You can download the CSV once the query finishes."
      else
        flash.now[:error] = "Oops, the query cannot be saved!!"
        render :new
      end
    end
  end
  </code></pre>
  
  <p>I found a question where a similar thing is being done. But somehow I couldn't get this work.
  <a href="https://stackoverflow.com/questions/6671795/get-parent-values-in-child-model">get parent values in child model</a></p>