Active Record errors value - Why doesn't this work?


#1

I’m creating an AR object in my controller and then attempting to add
error messages to it:

if (master_storeids.nil?)
@item.errors.add_to_base ‘No store is selected’
end

This works without error but when it comes time for AR to add the
record, it apparently initializes the errors because the message that I
added does not cause the AR add to fail as you would expect.

Even when there is a validation error in AR the message that I added
does not show up in the list of errors on the resulting page.

So, am I doing something wrong? If not, how can I add my controller
errors to the AR errors so that they are reported on the resulting page
(and cause AR to not add the record)?


#2

Anyone? Any ideas at all?

This input form has fields that are not directly part of the record(s)
being added. I need some way to detect errors in those fields and
report to user when form is redisplayed with errors.


#3

What code are you using to display the errors in the view?

On 19 Feb 2006 16:33:08 -0000, Richard W. <


#4

Richard W. wrote:

record, it apparently initializes the errors because the message that I
added does not cause the AR add to fail as you would expect.

Even when there is a validation error in AR the message that I added
does not show up in the list of errors on the resulting page.

So, am I doing something wrong? If not, how can I add my controller
errors to the AR errors so that they are reported on the resulting page
(and cause AR to not add the record)?

valid? calls errors.clear, so you’d have to do:

if @item.valid? && master_storeids
[SAVE/ADD ITEM]
elsif master_storeids.nil?
@item.errors.add_to_base ‘No store is selected’
end


We develop, watch us RoR, in numbers too big to ignore.


#5

I want to use the “standard” error display built by the scaffold. You
know the one where there is a message at the top of the form and the AR
field in error is highlighted.

This works fine for AR field errors but I can’t seem to add errors to it
(from outside the class by using the AR object’s add_to_base method.

Help anyone?


#6

Except with that approach you have to include this logic each time you
are doing a save in the controller. I would suggest this is business
logic tied to the model and therefore he should be using the validate
method.

def validate
if master_storeids.nil?
errors.add(“No store is selected”)
end
end

See page 267 in the Agile Rails book.

Michael


#7

Unfortunately storeids is not a field of the masters table so I don’t
think that will work.