[英]Generate Rows And Columns from Rails Console
I have a small predicament. 我有一个小困境。
I have a table called users. 我有一个称为用户的表。 The table users has relationship with another table called user notification.
表用户与另一个称为用户通知的表有关系。 Here is the migration for the user table:
这是用户表的迁移:
create_table "user_notifications", force: :cascade do |t|
t.belongs_to :user
t.integer "other_user"
t.integer "unseen_count", default: 0
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The problem is that when I create a new user then the table is populated with the row of the new user. 问题是,当我创建一个新用户时,该表将填充新用户的行。 How do I add the row to all the existing users.
如何将行添加到所有现有用户。 It is needed for the function of the app.
应用功能需要它。 Also I am using putty to connect to the server so the only tool I have is the rails console.
另外,我使用腻子连接到服务器,所以我唯一的工具是rails控制台。
Example: I have 60 users. 示例:我有60个用户。 How do I have it so all 60 users get a row in the new table using the rails console.
我如何拥有它,以便所有60位用户使用rails控制台在新表中获得一行。
Edit: This is the method I use whenever a user is signed up. 编辑:这是我在用户注册后使用的方法。 Can I use this method within the rails console or create a deviation of this?
我可以在Rails控制台中使用此方法还是创建偏差?
user.rb: user.rb:
after_create :create_user_notification
def create_user_notification
UserNotification.create(:user_id => self.id)
end
Thank you in advance. 先感谢您。
If I understand you correctly you want to add a notification to each user record. 如果我对您的理解正确,那么您想向每个用户记录添加一个通知。
Given that you have models that look something like this: 假设您有一些看起来像这样的模型:
class User
has_many :user_notifications
end
class UserNotification
belongs_to :user
end
To insert a record for each user you would do something like this: 要为每个用户插入一条记录,您需要执行以下操作:
User.all.find_in_batches(batch_size: 10).each do |u|
u.user_notifications.create(message: 'Hello dear')
end
.find_in_batches
might not really matter if you have 60 records but if you have 60,000 your server will run out of memory. 如果您有60条记录,
.find_in_batches
可能并不重要,但是如果您有60,000条,则服务器将耗尽内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.