Search code examples
ruby-on-railsassociationsmessage

Rails how to get a particular error message on association


I'm actually having a hard time figure out how to get a first error message related to a particular association. In my form, I must display errors under every related fields such as :

= f.text_field :price, class: 'form-control'
  - if @item.errors.has_key? :price
    = content_tag :span, @item.errors[:price].first, class: 'form-error'

This works fine on model base attributes. However, my Item model is linked to another model via a polymorphic association. When displaying errors.full_messages, I get ["Attachments name doit être rempli(e)"]. Here is the relation :

has_many :attachments, as: :attachable, dependent: :destroy
accepts_nested_attributes_for :attachments
validates :name, presence: true

How can I do in order to get the error returned by this association?


Solution

  • Ok I finally found the solution using @post.errors.inspect. Here is what I needed to do :

    @post.errors[:'attachments.name'].first
    

    Hope it will help poeple facing the same issue