1
<%= 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?

4

2 回答 2

6

We've had this working before

There are three things to consider:

All of these will give you the ability to either control, or access, the validation error message from your parent model. I think the issue is that as your models are "decoupled", making them independent - which means their error messages won't be available unless you make it so

Here's what I'd do


Validates Associated

#app/models/article.rb
class Article < ActiveRecord::Base
   has_many :photos
   validates_associated :photos
   accepts_nested_attributes_for :photos
end

I've not used this in anger - it should collate the error messages from your associated model, giving you the ability to display the error through your @article object. I'm not sure whether this will work, but it seems to be recommended by Rails core dev team:

You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, valid? will be called upon each one of the associated objects.

--

Reject If

You can use the reject_if method on your accepts_nested_attributes_for. This provides its own message, but will only be for the associated data (IE not based on the validations in your child model):

#app/models/article.rb
class Article < ActiveRecord::Base
   ...
   accepts_nested_attributes_for :photos, reject_if: {|attributes| attributes[:x].blank? } 
end

It also seems you won't get any messages with this! (I'll leave it in to give you an option)

--

Inverse_Of

This is the way we managed to get the associative error messages to show. It basically gives your models access to the data in each other - allowing you to refer to them directly:

#app/models/article.rb
class Article < ActiveRecord::Base
   has_many :photos, inverse_of: :article
end

#app/models/photo.rb
class Photo < ActiveRecord::Base
   belongs_to :article, inverse_of :photos
end

This gives you the ability to call their data, which should populate the errors object.

于 2014-09-18T17:52:25.317 回答
1

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
于 2014-09-18T15:12:55.077 回答