如何向我的 rails 模型添加新属性?

How can I add new attributes to my rails models?

我使用以下方法创建了一个模型:rails g model category 现在我想给那个模型添加一些属性,比如名字

所以我去了模型并添加了行 attribute :name

class Category < ApplicationRecord
  attribute :name
  #has_many :posts
end

这是我的控制器的样子:

class CategoriesController < ApplicationController

  #def permitted_params
   # params.require(:category).permit(:name)
  #end

  def index

  end

  def new
  end

  def create
    #category.create(permitted_params)
  end

  def edit
  end

  def update
  end

  def show
  end

  def destroy
  end
end

然后我 运行 命令:rails db:migrate 我想在我的数据库中添加一些东西来测试它。

我使用 rails 控制台并尝试添加类别:

我需要做什么才能将名字写入数据库?

要向模型添加属性,您应该使用此命令:

rails g migration AddNameToCategory name:string
rails db:migrate

虽然 rails 生成器已经在为您指定的属性创建数据库迁移,但您需要创建新的迁移以添加新的属性/数据库列。查看迁移指南:

https://edgeguides.rubyonrails.org/active_record_migrations.html

要创建新迁移,您可以 运行:

rails g migration add_categories_name

在迁移中更改方法:

add_column :categories, :name, :string

然后 运行 再 rake db:migrate

同时从您的模型中删除对属性的调用。

您在模型中定义的属性是虚拟属性,不会将任何内容写入数据库。

您必须定义迁移以将 columns/attributes 添加到数据库。

步骤: 1. 从 category.rb

中删除 attribute :name
  1. 创建 rails 迁移 rails g migration add_fields_to_categories name:string attribute2:type attribute3:type

  2. 运行 rails db:migrate

  3. 重新打开控制台并创建一个具有名称属性的新类别。

  4. 现在检查