我有一个模型令牌,它有一个字段token_number,我需要自动递增(从1001开始),当且仅当用户没有提供它.问题是,由于用户可以选择提供此字段,所以我无法准确地查询数据库并询问最大的token_number.我在这个论坛上找到了一个答案,但我确信必须有一个更好的方法来执行sql语句?
Auto increment a non-primary key field in Ruby on Rails
解决方法
对我有兴趣的问题不幸的是,rails并没有提供自动增加列的方法,所以我们必须借助于几乎没有自动化的sql.我在Rails 3.0.7中尝试使用Postgresql作为我的数据库,它的工作原理,希望这将是有用的:
为token_number PGSql Documentation创建序列
class CreateTokens < ActiveRecord::Migration def self.up create_table :tokens do |t| t.string :name t.integer :token_number t.timestamps end execute "CREATE SEQUENCE tokens_token_number_seq START 1001" end def self.down drop_table :tokens execute "DROP SEQUENCE tokens_token_number_seq" end end
现在,由于用户手动设置了token_number的可能性,所以只有在没有设置的时候才需要生成token_number.有了我们,
class Token < ActiveRecord::Base # Generate the sequence no if not already provided. before_validation(:on => :create) do self.application_no = next_seq unless attribute_present?("application_no") end private def next_seq(column = 'application_no') # This returns a PGresult object [http://rubydoc.info/github/ged/ruby-pg/master/PGresult] result = Token.connection.execute("SELECT nextval('tokens_token_number_seq')") result[0]['nextval'] end end
一个样品运行.请注意,对于第一个令牌,我没有设置token_number,它会生成token_number序列,第二个我分配.
ruby-1.9.2-p0 > token = Token.new => #<Token id: nil,name: nil,token_number: nil,created_at: nil,updated_at: nil> ruby-1.9.2-p0 > token.save sql (0.8ms) BEGIN sql (1.7ms) SELECT nextval('tokens_token_number_seq') sql (6.6ms) SELECT tablename FROM pg_tables WHERE schemaname = ANY (current_schemas(false)) sql (33.7ms) INSERT INTO "tokens" ("name","token_number","created_at","updated_at") VALUES (NULL,1001,'2012-03-02 12:04:00.848863','2012-03-02 12:04:00.848863') RETURNING "id" sql (15.9ms) COMMIT => true ruby-1.9.2-p0 > token = Token.new => #<Token id: nil,updated_at: nil> ruby-1.9.2-p0 > token.token_number = 3000 => 3000 ruby-1.9.2-p0 > token.save sql (0.8ms) BEGIN sql (1.5ms) INSERT INTO "tokens" ("name",3000,'2012-03-02 12:04:22.924834','2012-03-02 12:04:22.924834') RETURNING "id" sql (19.2ms) COMMIT => true ruby-1.9.2-p0 >