2

Working on creating a conditional validation for my model. To check for this I need to check if the Parent.parent_attribute == "true"

validates :departure_date, presence: true, future: true, :if => :awesome_method?
 belongs_to :parent


 def awesome_method?
   if @parent.parent_attribute == "true"
     true
   else
     false
   end
 end

Currently @parent.parent_attribute is returning nil even though the payload has it. I think I'm running into an issue where it can't access the parent_attribute because it hasn't saved yet... How do I perform a check that the parent has a value before setting a validation?

Update For clarity's sake, I am creating the parent and the child simultaneously. When I try to use Parent.find... I get back

Couldn't find Parent with 'parent_id'=CORRECT_INVOICE_NAME

Update 2 There is a create in both the parent and the child but the following JSON is what creates the parent with child.

{
 “parent": {
   “parent_id": "PLZDONTSAVE",
   “data": 2525.25,
   “parent_attribute": true,

   “child_attributes":[
     { “child_toy": “123",
       “child_data": “ABC" }
   ]
 }
}

Parent controller

  def create
    @parent = Parent.new(parent_params)
    if @parent.save
      render json: @parent, status: :created, location: @parent
    else
      render json: @parent.errors, status: :unprocessable_entity
    end
  end

  def parent_params
    params.require(:parent).permit(:parent_id, :parent_attribute,
    child_attributes:[:child_toy, :child_data, ])
  end
CheeseFry
  • 1,299
  • 1
  • 21
  • 38

2 Answers2

4

Unless you define @parent somewhere, it will be nil, just as @foo and @bar. You can access an object linked via an association (like your belongs_to) by simply using parent without the "@".

So try this:

  def awesome_method?
    parent.parent_attribute == "true"
  end
tbreier
  • 214
  • 1
  • 8
3

I got it to work by updating both models with the following. With help from here

In the child model

belongs_to :parent, inverse_of: :child 

In the parent model

accepts_nested_attributes_for :children
has_many :children, inverse_of: :parent

That coupled with @tbreier's suggestion got the job done.

Community
  • 1
  • 1
CheeseFry
  • 1,299
  • 1
  • 21
  • 38