简体   繁体   English

如何在Rails控制台上的同一模型内创建的另一个表中添加新记录?

[英]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. 首先,你应该改变的表名userusers ,因为它的方便。 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.

相关问题 如何从同一表中的另一个记录更新记录? - How to update a record from another record in same table? Rails 4-如果在另一个表中不是特定记录,如何从一个表中选择数据? - Rails 4 - How to select data from a table if in another table is not a specific record? 如果从另一个模型创建新对象,则Django在模型上添加新字段 - Django add new field on model if new object is created from another model 如何更新 NULL 外键并在引用相同键的另一个表中创建新行? - How to update a NULL foreign key and create a new row within another table referencing the same key? 如何向依赖于另一个模型的Rails模型添加验证 - How to add a validation to rails model which depends on another model 创建记录时,Mysql触发器将id从一列复制到同一表中的另一列 - Mysql trigger to copy id from one column to another in same table when record is created SQL查询以在新表中为另一个表的所有ID插入相同记录 - SQL query to insert the same record for all the ids of another table in a new table 使用 if 语句创建触发器以在新记录后将新行添加到另一个表 - Creating a trigger to add new row to another table after new record using if statement 如何从控制台使用 Rails 3 活动记录插入 many_to_many 表 - How to insert into a many_to_many table using Rails 3 active record from the console 在提交后添加表单数据并从另一个表中获取数据以形成新记录 - PHP MySQL - Add Form Data and Get Data from Another Table to Form a New Record After Submit - Php MySQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM