如何将新记录添加到 Rails 控制台上同一模型中创建的另一个 table?
How to add new record to another table created within the same model on Rails console?
我已经使用这个命令创建了一个模型
rails g model UserPost postId:string postDesc:string
比我用
创建另一个 table
rails g migration CreateUser name:string email:string
所以,运行宁 rails console
,我只能在 user_posts
table 上添加记录,例如
user=UserPost.create(post_id:"My Post", post_desc:"This is my post")
我的问题是想知道如何在 user
table 上添加新记录?
使用 Sql,这是使用 table_name
作为
完成的
INSERT INTO TABLE user_posts values("My Post", "This is my post")
和
INSERT INTO TABLE users values("my_name", "my_email")
但在 Rails 上,我认为它使用了模特的名字。
注意:rake db:migrate
在特定时间已经 运行。
首先,您应该将 table user
table 的名称更改为 users
,这样比较方便。然后你应该为你的用户创建一个模型 table: rails g model user
。然后,您将能够在向帖子添加记录时向用户 table 添加记录:User.create(name: 'my_name', email: 'my_email')
.
更新
每个数据库 table 都应该有一个 rails 模型,除非它是一个连接 table
我已经使用这个命令创建了一个模型
rails g model UserPost postId:string postDesc:string
比我用
创建另一个 tablerails g migration CreateUser name:string email:string
所以,运行宁 rails console
,我只能在 user_posts
table 上添加记录,例如
user=UserPost.create(post_id:"My Post", post_desc:"This is my post")
我的问题是想知道如何在 user
table 上添加新记录?
使用 Sql,这是使用 table_name
作为
INSERT INTO TABLE user_posts values("My Post", "This is my post")
和
INSERT INTO TABLE users values("my_name", "my_email")
但在 Rails 上,我认为它使用了模特的名字。
注意:rake db:migrate
在特定时间已经 运行。
首先,您应该将 table user
table 的名称更改为 users
,这样比较方便。然后你应该为你的用户创建一个模型 table: rails g model user
。然后,您将能够在向帖子添加记录时向用户 table 添加记录:User.create(name: 'my_name', email: 'my_email')
.
更新 每个数据库 table 都应该有一个 rails 模型,除非它是一个连接 table