【发布时间】:2016-08-15 07:00:07
【问题描述】:
正在为我的模型创建条件验证。要检查这一点,我需要检查 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
【问题讨论】:
标签: ruby-on-rails ruby model