ruby - Access parent attribute in child model rails -


working on creating conditional validation model. check need check if 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 returning nil though payload has it. think i'm running issue can't access parent_attribute because hasn't saved yet... how perform check parent has value before setting validation?

update clarity's sake, creating parent , child simultaneously. when try use parent.find...

couldn't find parent 'parent_id'=correct_invoice_name

update 2 there create in both parent , child following json creates parent 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 

unless define @parent somewhere, nil, @foo , @bar. can access object linked via association (like belongs_to) using parent without "@".

so try this:

  def awesome_method?     parent.parent_attribute == "true"   end 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -