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,
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With