访问子模型rails中的父属性

时间:2016-04-21 21:01:15

标签: ruby-on-rails ruby model

为我的模型创建条件验证。要检查这一点,我需要检查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

目前@ parent.parent_attribute返回nil,即使有效负载有。我想我遇到了一个无法访问parent_attribute的问题,因为它尚未保存...如何在设置验证之前检查父项是否有值?

更新 为了清楚起见,我正在同时创建父母和孩子。 当我尝试使用Parent.find...时,我会回来

  

找不到包含'parent_id'= CORRECT_INVOICE_NAME

的家长

更新2 在父级和子级中都有一个创建,但是以下JSON是创建具有子级的父级的。

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

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

家长控制器

  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

2 个答案:

答案 0 :(得分:4)

除非您在某处定义@parent,否则它将是nil,就像@foo@bar一样。您只需使用belongs_to而不使用“@”即可访问通过关联链接的对象(例如parent)。

所以试试这个:

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

答案 1 :(得分:2)

我通过使用以下内容更新两个模型来实现它。在here

的帮助下

在儿童模特中

belongs_to :parent, inverse_of: :child 

在父模型中

accepts_nested_attributes_for :children
has_many :children, inverse_of: :parent

加上@tbreier的建议完成了工作。

相关问题