2
class Query < ActiveRecord::Base
  #relations
  has_one :r_job
  accepts_nested_attributes_for :r_job
end

class RJob < ActiveRecord::Base
  belongs_to :query
  validates_presence_of :analysis_type, :if => lambda {|job| job.query.process_r_job} 
end

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.

NoMethodError (undefined method `process_r_job' for nil:NilClass):
   app/models/r_job.rb:3:in `block in <class:RJob>'
   app/controllers/queries_controller.rb:9:in `create'

I digged in a bit and I found, job.query 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.

# app/views/queries/new.html.haml
=form_for @query, {:html => {:class=>"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 => f

  %fieldset
    =f.fields_for :r_job do |builder|
      =render "r_job_form", :f => builder
  %button.btn.btn-primary.small Go

#app/controller/queries_controller.rb
class QueriesController < 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 => "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

I found a question where a similar thing is being done. But somehow I couldn't get this work. get parent values in child model

Community
  • 1
  • 1
Deepak
  • 2,481
  • 2
  • 23
  • 28
  • possible duplicate of [accepts\_nested\_attributes\_for child association validation failing](http://stackoverflow.com/questions/935650/accepts-nested-attributes-for-child-association-validation-failing) – Mauricio Pasquier Juan Apr 02 '14 at 22:37

3 Answers3

0

You can do it with :inverse_of. It's already explained/answered here.

Community
  • 1
  • 1
Mauricio Pasquier Juan
  • 2,265
  • 3
  • 27
  • 39
0

Conditional lambda takes no parameters and is run in instance context, so this should work:

:if => lambda { query.process_r_job }

and consider a shorter notation:

if: 'query.process_r_job'
lokson
  • 565
  • 3
  • 15
-2

Refer the same question is asked in below link.

Rails accepts_nested_attributes_for child doesn't have parent set when validating

None of the answer is accepted.Because it can not be done.

Community
  • 1
  • 1
Soundar Rathinasamy
  • 6,658
  • 6
  • 29
  • 47