我使用以下方法创建了一个模型:rails g model category
现在我想向该模型添加一些属性,例如名称
所以我去了模型并添加了行 attribute :name
class Category < ApplicationRecord
attribute :name
#has_many :posts
end
这是我的 Controller 的样子:
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 控制台并尝试添加一个类别:
我需要做什么才能将名字写入数据库?
最佳答案
您在模型中定义的属性是一个虚拟属性,不会将任何内容写入数据库。
您必须定义迁移以将列/属性添加到数据库。
步骤:
1. 从 category.rb 中删除 attribute :name
创建一个 rails 迁移
rails g migration add_fields_to_categories name:string attribute2:type attribute3:type
运行
rails db:migrate
重新打开控制台并创建一个具有名称属性的新类别。
现在检查
关于ruby-on-rails - 如何向我的 Rails 模型添加新属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52644657/