2011-08-18 101 views
0

我創建模型用戶與字段ID,姓名,姓氏,年齡如何我可以創建一個模型,其中字段「ID」是不是自動增量ID,我需要手動輸入數字rails 3,如何創建id字段以手動輸入ID號?

run scaffold :

rails g scaffold user id:integer name:string lastname:string age:integer 

形式/views/users/_form.html.erb

<div class="field"> 
    <%= f.label :id %><br /> 
    <%= f.text_field :id %> 
    </div> 
    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :lastname %><br /> 
    <%= f.text_field :lastname %> 
    </div> 
    <div class="field"> 
    <%= f.label :age %><br /> 
    <%= f.text_field :age %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 

我是插入值

Id: 12345 
Name: paul 
Lastname: rivers 
Age: 24 

但創建顯示:

用戶已成功創建。在軌

Id: 1 
Name: paul 
Lastname: rivers 
Age: 24 

服務器顯示:

Started POST "/users" for 127.0.0.1 at Thu Aug 18 14:26:35 -0500 2011 
    Processing by UsersController#create as HTML 
    Parameters: {"commit"=>"Create User", "authenticity_token"=>"C8oBqh86CPmramr5yYRoIgufaQnKMBD5SSLOIrZ1mFo=", "utf8"=>"✓", "user"=>{"name"=>"paul", "id"=>"12345", "lastname"=>"rivers", "age"=>"24"}} 
WARNING: Can't mass-assign protected attributes: id 
    SQL (0.1ms) BEGIN 
    SQL (0.4ms) SHOW TABLES 
    SQL (0.4ms) describe `users` 
    AREL (0.4ms) INSERT INTO `users` (`lastname`, `name`, `age`, `created_at`, `updated_at`) VALUES ('rivers', 'paul', 24, '2011-08-18 19:26:35', '2011-08-18 19:26:35') 
    SQL (99.2ms) COMMIT 

我正在查看現場ID查詢不包括

編輯1

遷移:

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table :users, :id => false do |t| 
     t.integer :id 
     t.string :name 
     t.string :lastname 
     t.integer :age 

     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :users 
    end 
end 

該ID必須是primary_key

+0

複製? http://stackoverflow.com/questions/517869/id-field-without-autoincrement-option-in-migration – fredw

+1

我會建議你不要這樣做。通常,打破Rails約定並不好。 – inntran

+0

好吧,它的完美 – kalelc

回答

0

編輯您的遷移

create_table :users, :id => false do |t| 
    t.integer :id 
    ... 
end 
+0

humm,但我需要的ID是primary_key – kalelc

+0

@andres,結帳我的更新 – fl00r

+0

@floor,結帳我的遷移,是一樣的。 – kalelc

相關問題