Oops, minor syntax errors: the first debug version of the
before_validation code should have been:
def before_validation
$logger.info %(postcode before: "#{address_postcode}") # =>
postcode
before: "v1m 3w3"
address_postcode = address_postcode.to_s.upcase.gsub(/ /,
'''')
# The empty output, below, is not what is expected...
$logger.info %(postcode after: "#{address_postcode}") # =>
postcode after: ""
end
On Wed, 12 Jan 2005 21:41:25 -0800, Bob Sidebotham
<bob.sidebotham-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> I have a controller that does something like:
>
> Customer.update(id, @params["customer"])
>
> and an AR object, Customer, with this code:
>
> def before_validation
> address_postcode = address_postcode.to_s.upcase.gsub(/ /,
'''')
> end
>
> I was hoping that this would do a conversion on the postal code before
> storing the record, but it doesn''t.
>
> I teased this apart a little, with the following results ($logger set
> to the standard logger):
>
> def before_validation
> $logger.info("postcode before: #{address_postcode}") # =>
postcode
> before: "v1m 3w3"
> address_postcode = address_postcode.to_s.upcase.gsub(/ /,
'''')
> # The output, below, is not what is expected...
> $logger.info("postcode after: #{address_postcode}") # =>
postcode after: ""
> end
>
> If I change it to:
>
> def before_validation
> $logger.info %(postcode before: "#{address_postcode}") # =>
postcode
> before: "v1m 3w3"
> pc = address_postcode
> address_postcode = pc.to_s.upcase.gsub(/ /,"")
> # The output, below, is now correct.
> $logger.info %(postcode after: "#{address_postcode}") # =>
postcode
> after: "V1M3W3"
> end
>
> So the above is problem #1 (i.e. for some reason, in this
> before_validation method, I have to copy the column value before
> modifying it, otherwise it ends up nil, I think).
>
> The second problem, is that no matter what I set it to in the
> before_validation method, the value still ends up, in the database, as
> "v1m3w3" (i.e. the unmodified value). The log shows this, with
the
> modified value being logged from the before_validation method, and the
> unmodified value being used in the subsequent SQL update statement.
>
> I''m running with the latest versions of all the appropriate
software components.
>
> Some help with this would be much appreciated.
>
> Thanks,
> Bob
>
> P.S. I''m not sure this is really an appropriate use of the
> before_validation hook--if that''s the case, is there another way
to
> accomplish this? (Other than putting the logic directly in the
> controller, prior to calling update...).
>