Search code examples
ruby-on-railsnested-attributesnested-form-for

How can I access the validation errors for my nested attributes?


<%= form_for @article , :html => {:multipart=> true} do |f| %>
  <% if @article.errors.any? %>
    <ul>
      <% @article.errors.full_messages.each do |msg| %>
       <li><%= msg %></li>
      <% end %>
    </ul>
  <% end %>

Above is a snippet of my form, I can access validations for the articles i.e. validates_presence of :author, :title however I can't access the validations I set for my nested_attributes, which happen to be photos. Any ideas on how to show error messages?


Solution

  • Photo model:

      Class Photo < ActiveRecord::Base
      belongs_to :article     
      validates :author, presence: true
      end
    

    Article model:

      class Article < ActiveRecord::Base
      has_many :photos
      accepts_nested_attributes_for :photos
      validates_presence_of :author
      end