Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error messages of nested attributes's required field are not displayed

In my case, I have a client who has many tasks (which requires :detail and :completion_date fields.). I've been building a nested model form like the following:

= simple_form_for @client do |f|
  = f.simple_fields_for :tasks do |task|
    = task.input :detail
    = task.input :completion_date
  = f.submit

When the form is submitted without either empty 'detail' or 'completion_date' field, the form is re-render but without any error messages displayed.

I've been tried to look for solutions all day. None of those mentioned about failing validation of the nested object's attributes.

Hope anybody can help! Thanks,

like image 795
Pirun Seng Avatar asked Mar 17 '16 16:03

Pirun Seng


1 Answers

Rails does not validate associated objects by default . You need to use the validates_associated macro.

Example:

class Client < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
  # Do not add this on both sides of the association
  # as it will cause infinate recursion.
  validates_associated :tasks
end

class Task < ActiveRecord::Base
  belongs_to :client
  validates_presence_of :name
end

@client = Client.create(tasks_attributes: [ name: "" ])
@client.errors.messages
=> {:"tasks.name"=>["can't be blank"], :tasks=>["is invalid"]}

The indiviaual validations errors for the associated records are not aggregated in the parent. To display the errors for the child records you need to iterate through them and call errors.full_messages.

@client.tasks.each do |t|
  puts t.errors.full_messages.inspect
end

Or when using fields for:

= simple_form_for @client do |f|
  = f.simple_fields_for :tasks do |task|
    - if task.object.errors.any?
       - task.object.errors.full_messages.each do |message|
         p.error 
           = message
    = task.input :detail
    = task.input :completion_date
  = f.submit
like image 65
max Avatar answered Oct 12 '22 14:10

max