在我的 Rails 应用程序中,我有两个具有 has_many/belongs_to 关系的模型 -Farmer
和Animal
。
class Farmer
has_many :animals
accepts_nested_attributes_for :animals
end
class Animal
belongs_to :farmer
validates_numericality_of :age, less_than: 100
end
我想实现create
方法Farmer
也可以创建嵌套动物。
class FarmerController < ApplicationController
def create
@farmer = Farmer.new(farmer_params)
if @farmer.save
render json: @farmer
else
render json: { errors: @farmer.errors }, status: :unprocessable_entity
end
end
private
def farmer_params
params.require(:farmer).permit(
:name,
{ animals_params: [:nickname, :age] }
)
end
end
Animal
验证age
字段,如果验证失败,方法将返回错误哈希。所以当我尝试使用以下 json 创建农民时
{
"farmer": {
"name": "Bob"
"animals_attributes: [
{
nickname: "Rex",
age: 300
}
]
}
}
我收到此错误:
{
"errors": {
"animals.age": [
"must be less than 100"
]
}
}
但是我想将错误作为嵌套哈希(前端需求的原因(获取,就像这样:
{
"errors": {
"animals":[
{
age: [
"must be less than 100"
]
}
]
}
}
我怎样才能做到这一点?
没有找到标准的方法,所以我用自己的解析器解决了它。