views:

58

answers:

2

I have a form that contains the data to create a Product object. The Product has a relationship with an Image like so:

has_one :image

In my view I have a file input like so:

<%= f.file_field :image_file %>

In my Product model I have:

  def image_file=(input_data)
    self.image = Image.new({:image_file => input_data})
  end

The image model knows how to deal with the input_data and has validation rules for it. The problem is that if the validation fails, my product gets created without an image.

How do I make the validation errors ripple back to the Product, so that the Product does not get created at all and so I can show the errors on the form?

As I'm new to Rails, if I'm doing it all wrong please tell me so.

+1  A: 

You can use validates_associated for that

Gareth
Thanks, that seems to be what I was looking for. However, it outputs a default error message, it doesn't seem like I can get to the actual error message from the failed validation, can I?
JRL
A: 

I ended up doing it by creating a custom validator:

validate :associated_image

This is the method:

def associated_image
  if image && !image.valid?
    image.errors.each { |attr, msg| errors.add(:image_file, msg)}
  end
end

Thanks to Gareth for pointing me to validates_associated, but the problem with it is that you lose the actual error messages from the associated object.

JRL