Let's say I have this:
class Author < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
end
class Post < ActiveRecord::Base
belongs_to :author
validates_presence_of :name
end
The front-end has a form that saves it all at once, with one author and as much post as you want, sending this input:
attributes = { name: "lorem",
posts_attributes: [
{ name: 'lorem',
order: 1 },
{ name: 'lorem',
order: 2 }
]
}
author = Author.new(attributes)
author.save
My question is about validation. How can I send back validation to the front-end so that it can understand in the form which Post
instance has failed? Right now, with an input like:
attributes = { name: "lorem",
posts_attributes: [
{ order: 1 },
{ name: 'lorem',
order: 2 }
]
}
author = Author.new(attributes)
author.save
author.errors.messages
will return something like {:"posts.name"=>["must be present"]}
with no indication to know which name
field it is in the form to send the validation error to, since there are more than one post being created.
How to change this error to get this indication, by maybe using the order
attribute that each Post
instance has too?
EDIT : instead of a custom validation error including the number order in the error message, I'd like another key-value pair like order: 1
so that it is easier to handle in the front-end
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…