Ruby on rails Rails迁移t.attown\u to:user,添加自定义列名seller\u id?
我正在尝试通过执行以下操作将卖家id添加到迁移中的项目模型中:Ruby on rails Rails迁移t.attown\u to:user,添加自定义列名seller\u id?,ruby-on-rails,ruby,migration,Ruby On Rails,Ruby,Migration,我正在尝试通过执行以下操作将卖家id添加到迁移中的项目模型中: rails g模型商品标题:字符串描述:文本价格:bigint状态:整数已发布\u日期:日期卖方:所属\u所属 这当然不管用 最后,我希望在我的items表中看到seller_id,它将item模型与用户模型关联起来 目前,我的迁移如下所示: class CreateItems < ActiveRecord::Migration def change create_table :items do |t|
rails g模型商品标题:字符串描述:文本价格:bigint状态:整数已发布\u日期:日期卖方:所属\u所属
这当然不管用
最后,我希望在我的items表中看到seller_id,它将item模型与用户模型关联起来
目前,我的迁移如下所示:
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :title
t.text :description
t.bigint :price
t.integer :status
t.datetime :published_date
t.belongs_to :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
class CreateItems
seller\u id
,那么您所拥有的就足够了。使用rake db:migrate
运行迁移后,您将在db/schema.rb
文件中看到带有外键的实际表结构user\u id
rake db:migrate
seller\u id
,那么您所拥有的就足够了。使用rake db:migrate
运行迁移后,您将在db/schema.rb
文件中看到带有外键的实际表结构user\u id
rake db:migrate
只需在迁移文件中明确定义所需内容,并将必要的关系添加到模型中,而不是t.U。您可以使用:
t.integer :seller_id, index: true, foreign_key: true
在您的模型中,您可以通过几种方式来实现这一点,如果您还希望在项目实例中引用您作为卖家的关系,那么在项目类中创建关系:
belongs_to :seller, class_name: 'User'
在用户类中:
has_many :items, foreign_key: :seller_id
或者,如果要从项目中将其作为用户引用,则:
belongs_to :user, foreign_key: :seller_id
就编辑生成器而言,这是模型生成器工作的默认方式,在我看来,我喜欢保持默认方式。不过,我建议您在需要创建一些定制/特例时创建自己的rails生成器或自己的rake任务。要了解如何创建自己的生成器,我将向您介绍ruby on rails创建生成器的官方指南:只需在迁移文件中明确定义所需内容,并将必要的关系添加到模型中,而不是t。您可以使用:
t.integer :seller_id, index: true, foreign_key: true
在您的模型中,您可以通过几种方式来实现这一点,如果您还希望在项目实例中引用您作为卖家的关系,那么在项目类中创建关系:
belongs_to :seller, class_name: 'User'
在用户类中:
has_many :items, foreign_key: :seller_id
或者,如果要从项目中将其作为用户引用,则:
belongs_to :user, foreign_key: :seller_id
就编辑生成器而言,这是模型生成器工作的默认方式,在我看来,我喜欢保持默认方式。不过,我建议您在需要创建一些定制/特例时创建自己的rails生成器或自己的rake任务。要了解如何创建自己的生成器,我将向您介绍RubyonRails创建生成器的官方指南:在您的迁移中,您可以使用
t.belongs_to :seller, foreign_key: {to_table: :users}
在您的迁移中,您可以使用
t.belongs_to :seller, foreign_key: {to_table: :users}
“添加自定义列名seller_id”就是这个问题的具体内容。这是一项要求。“添加自定义列名卖方id”是问题的具体内容。这是一项要求。