【问题标题】:How I can change the model attribute name on ruby on rails如何在 ruby​​ on rails 上更改模型属性名称
【发布时间】:2019-02-27 20:14:09
【问题描述】:

我想把假变量名改成新的,所以我创建了真和新的,但旧的和假的仍然存在!

  • 怎样才能去掉假的

    irb(main):001:0> item = Item.last Item Load (0.3ms) SELECT "items".* FROM "items" ORDER BY "items"."id" DESC LIMIT ? [["LIMIT", 1]] => #<Item id: 6, title: "Make a cake for your darling", description: "She loves furit ", created_at: "2019-02-27 18:04:15", updated_at: "2019-02-27 18:04:15", user_id: 2, complated_at: nil, completed_at: nil> irb(main):002:0>

我打错字了,应该是“完成”

我能做什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:
    rails g migration remove_complated_at_from_items complated_at:datetime
    

    这一行生成这些代码

    class RemoveComplatedAtFromItems < ActiveRecord::Migration[5.2]
      def change
        remove_column :items, :complated_at, :datetime
      end
    end
    

    我当前的 schema.rb 文件

    ActiveRecord::Schema.define(version: 2019_02_27_204841) do
      create_table "items", force: :cascade do |t|
        t.string "title"
        t.text "description"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.integer "user_id"
        t.datetime "completed_at"
        t.datetime "complated_at"
      end
    

    现在让我们运行 rails db:migrate

    $ rails db:migrate

    == 20190227204841 RemoveComplatedAtFromItems: migrating =======================
    -- remove_column(:items, :complated_at, :datetime)
       -> 0.0038s
    == 20190227204841 RemoveComplatedAtFromItems: migrated (0.0039s) ==============
    

    似乎一切都很好!让我们检查一下 schema.rb!

    ActiveRecord::Schema.define(version: 2019_02_27_204841) do
      create_table "items", force: :cascade do |t|
        t.string "title"
        t.text "description"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.integer "user_id"
        t.datetime "completed_at"
      end
    

    现在一切都很好。最后一个让我们检查一个对象!

     rails c
    irb(main):001:0> item = Item.last
      Item Load (0.3ms)  SELECT  "items".* FROM "items" ORDER BY "items"."id" DESC LIMIT ?  [["LIMIT", 1]]
    => #<Item id: 6, title: "Make a cake for your darling", description: "She loves furit ", created_at: "2019-02-27 18:04:15", updated_at: "2019-02-27 18:04:15", user_id: 2, completed_at: nil>
    

    完成!

    【讨论】:

      【解决方案2】:

      不要删除列。重命名就好了。

      新建一个迁移并放上代码:

      rename_column :items, :complated_at, :completed_at

      【讨论】:

      • 谢谢! :) 对于那些尝试这样做的人:我运行 rails g migration RenameColumnsComplatedAt 然后将迁移更改为:class RenameColumnsComplatedAt &lt; ActiveRecord::Migration[6.1] def change rename_column :tasks, :complated_at, :completed_at end end
      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-20
        • 1970-01-01
        • 2018-04-20
        • 1970-01-01
        相关资源
        最近更新 更多