在我的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"
]
}
]
}
}
我该如何实现?
答案 0 :(得分:0)
找不到标准的方法,所以我用自己的解析器解决了该问题。