Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

ruby on rails - How to find the record that failed in validation with nested attributes on a has_many association?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is the solution I need: https://bigbinary.com/blog/errors-can-be-indexed-with-nested-attrbutes-in-rails-5

Basically adding index_errors: true to the has_many association does the trick.

This leads to error to be generated this way, in my usecase: {:"posts[0].name"=>["must be present"]}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...