I want to remove the leading and training spaces for most of the
resources in my rails application
For a new POST request, rails does the xml parsing and passes the params
hash to the controller. Some of the parameters have leading and/or
trailing whitespaces which are causing problems (e.g. new resources
being created rather than using the old ones). I don’t want to put the
code in all the controllers to strip the whitespaces for different
resources/params.
I did find the following pattern:
Is there another better approach to solve this? I was thinking of
configuring controller xml parser to remove these whitespaces. Is that
possible?
Thanks,
-Rakesh
On Jun 25, 2010, at 1:26 PM, Rakesh A. wrote:
I did find the following pattern:
Rails pattern: trim spaces on input | I gotta have my orange juice.
Is there another better approach to solve this? I was thinking of
configuring controller xml parser to remove these whitespaces. Is that
possible?
That looks like the ideal way to do it. This sort of thing belongs in
the model as it will stop you from making a mistake that one time you
use ./script/console to make that one change…
I’m sure you could modify the XML parser, but why? The moment you add
another way to access the data you’d have to do it there as well. And
what if you have a field that you want to allow white space?
-philip
This pattern is not working for find_or_create_by_***:
I am getting ConstraintException:column *** is not valid for the
resources that are already in the database.
I understand that this is because trimmed_field is using
before_validation callback.
Any idea how to fix this?
Thanks,
-Rakesh
Some more information about my failure scenario:
Code in my controller’s create:
XXX.find_or_create_by_yyy(params[:input])
Here is the spec code that is failing
xxx = XXX.create!(:yyy => ‘abc’)
#Send a post request to the controller with a resource that already
exists
#but include leading and training blank spaces
post :create, {:input => {:yyy => ’ abc '}}
I am using the pattern defined here to strip the whitespaces:
However, that only happens at before_validation. So find is not stipping
the whitespaces from my post request. Now it tries to create a new
resource and the whitespaces are stripped (before_validation callback)
causing ConstraintException:column yyy is not valid for the resources
that are already in the database.
Thanks,
-Rakesh