【问题标题】:rails 3, how can i create id field to manually enter the ID number?rails 3,如何创建 id 字段以手动输入 ID 号?
【发布时间】:2011-08-18 19:33:36
【问题描述】:

我正在使用字段 id、name、lastname、age 创建模型用户我如何创建字段“id”不是自动增量 ID 的模型,我需要手动输入数字

运行脚手架:

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

在 Rails 服务器中显示:

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

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

编辑您的迁移

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

【讨论】:

  • 嗯,但我需要 id 是 primary_key
  • @floor,检查我的迁移,是一样的。
猜你喜欢
  • 1970-01-01
  • 2014-08-31
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多