[英]How to add new record to another table created within the same model on Rails console?
I have created a model using this command 我已经使用此命令创建了一个模型
rails g model UserPost postId:string postDesc:string
than after I created another table with 比我创建另一个表之后
rails g migration CreateUser name:string email:string
So, running rails console
, I was only able to add records on user_posts
table with for example 因此,在运行rails console
,我只能使用例如在user_posts
表上添加记录
user=UserPost.create(post_id:"My Post", post_desc:"This is my post")
My question is to know how to add new records on user
table? 我的问题是知道如何在user
表上添加新记录? With Sql, this is done using table_name
as 在Sql中,使用table_name
作为
INSERT INTO TABLE user_posts values("My Post", "This is my post")
and 和
INSERT INTO TABLE users values("my_name", "my_email")
but on Rails, I think it uses model's name. 但是在Rails上,我认为它使用模型的名称。
Note: rake db:migrate
has been run at its specific time. 注意: rake db:migrate
已在其特定时间运行。
First of all, you should change table name of user
table to users
since it's convenient. 首先,你应该改变的表名user
表users
,因为它的方便。 Then you should create a model for your users table: rails g model user
. 然后,您应该为用户表创建一个模型: rails g model user
。 Then you will be able to add records to users table as you adding records to the posts: User.create(name: 'my_name', email: 'my_email')
. 然后,您可以在将记录添加到帖子中的同时向用户表添加记录: User.create(name: 'my_name', email: 'my_email')
。
UPD You should have a rails model to each db table unless it's a join table UPD您应该对每个数据库表都有一个Rails模型,除非它是一个联接表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.