Further to postgres on Rails in Fedora 18 but OT
Bruno Wolff III
bruno at wolff.to
Thu May 16 14:11:16 UTC 2013
On Thu, May 16, 2013 at 19:57:46 +1000,
Roger <arelem at bigpond.com> wrote:
>
>In sqlite, the string tables contain numbers so the rails to_i
>changes them to integer for adding.
>How can I do this with postgres please?
You can cast text to integer using ::integer. For example:
bruno=> select '123'::text::integer;
int4
------
123
(1 row)
>Thanks in advance
>Roger
>
>The reason I didn't make the numeric fields integer, is because Rails
>likes to have a select system for fields inputting integers and I do
>not want this.
If you do this, I recommend putting a constraint on the fields so that
they can only be integers. You can use regular expressions to do the
matching.
>I have been searching on google all day for answers but as usual,
>responses from Rails officianados is curt and lacks explanation.
For postgres questions I would start by looking at the postgres documentation.
It is very good.
In this case it might not be obvious where to look, but what you want is
covered under type casts.
http://www.postgresql.org/docs/9.2/static/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS
Note in my example above I used the :: notation because it is a lot more
convenient to type than using the SQL standard CAST function. But you
don't want to use that in real code as it will make it harder to switch
databases later.
If you want to using formatting when converting between strings and numbers
(mostly going from numeric types to string types) you can look at:
http://www.postgresql.org/docs/9.2/static/functions-formatting.html
More information about the users
mailing list