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.