I have an attribue attempts in database of integer type (initial value is 0 )
When I do @user.attempts += 1 , it throws TypeError: can't convert Fixnum into String
So, I conclude that rails does not convert attributes automatically according to their datatype.
When I do
@user.attempts.to_i +=1
it throws NoMethodError: undefined method 'to_i=' for "0":String
and when I do,
@user.attempts.to_i = @user.attempts.to_i + 1
it throws NoMethodError: undefined method 'to_i=' for "0":String again.
And this,
@user.attempts = @user.attempts.to_i + 1
works fine.
I think the reason is that when I do @user.attempts.to_i + 1 , it actually changes the @user.attempts on left side .
Can somebody throw some light on this behavior ?
EDIT
Migration
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :email_pass
t.integer :attempts
t.timestamps
end
end
end
Create table script
-- Table: users
-- DROP TABLE users;
CREATE TABLE users
(
id serial NOT NULL,
email character varying(255),
email_pass character varying(255),
attempts character varying(255),
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
);
ALTER TABLE users
OWNER TO jashwant;
I see that in db attempts is character type.
So, what should be the proper way to alter its datatype.
And I also stand out for my first question, whats the reason for that type conversion ?
When you use
+=like this :it is the same as :
And when you do,
it is the same as :
So you are actually calling
#to_i=on@user.attemptswhich does not exist.When you do
@user.attempts = @user.attempts.to_i + 1, your call is the same as this one :which exists and so works fine.