0

我在类型attempts的数据库中有一个属性integer(初始值为 0 )

当我这样做时@user.attempts += 1,它会抛出TypeError: can't convert Fixnum into String

因此,我得出结论,rails 不会根据属性的数据类型自动转换属性。

当我做

@user.attempts.to_i +=1

它抛出NoMethodError: undefined method 'to_i=' for "0":String

当我这样做时,

@user.attempts.to_i = @user.attempts.to_i + 1

它再次抛出NoMethodError: undefined method 'to_i=' for "0":String

和这个,

@user.attempts = @user.attempts.to_i + 1

工作正常。

我认为原因是当我这样做时@user.attempts.to_i + 1,它实际上改变了@user.attempts左侧。

有人可以对这种行为有所了解吗?

编辑

移民

    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

创建表脚本

-- 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;

我看到在 dbattempts中是字符类型。

那么,改变其数据类型的正确方法应该是什么。我的第一个问题也很突出,这种类型转换的原因是什么?

4

2 回答 2

2

在迁移中使用 change_column:

rails g migration change_attempts_to_integer_for_users

...

打开并编辑迁移

def self.up
  change_column(:users, :attempts, :integer)
end

def self.down
  change_column(:users, :attempts, :text)
end

运行迁移。

于 2012-10-21T15:01:11.457 回答
1

当你+=这样使用时:

something += 1

它与以下内容相同:

something = something + 1

当你这样做时,

obj.method = val

它与以下内容相同:

obj.method=(val)

所以你实际上是在调用#to_i=@user.attempts存在的。

当您这样做时@user.attempts = @user.attempts.to_i + 1,您的呼叫与此呼叫相同:

@user.attempts=(@user.attempts.to_i + 1)

它存在,所以工作正常。

于 2012-10-21T14:32:59.250 回答