[英]Generate Rows And Columns from Rails Console
我有一个小困境。
我有一个称为用户的表。 表用户与另一个称为用户通知的表有关系。 这是用户表的迁移:
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
问题是,当我创建一个新用户时,该表将填充新用户的行。 如何将行添加到所有现有用户。 应用功能需要它。 另外,我使用腻子连接到服务器,所以我唯一的工具是rails控制台。
示例:我有60个用户。 我如何拥有它,以便所有60位用户使用rails控制台在新表中获得一行。
编辑:这是我在用户注册后使用的方法。 我可以在Rails控制台中使用此方法还是创建偏差?
user.rb:
after_create :create_user_notification
def create_user_notification
UserNotification.create(:user_id => self.id)
end
先感谢您。
如果我对您的理解正确,那么您想向每个用户记录添加一个通知。
假设您有一些看起来像这样的模型:
class User
has_many :user_notifications
end
class UserNotification
belongs_to :user
end
要为每个用户插入一条记录,您需要执行以下操作:
User.all.find_in_batches(batch_size: 10).each do |u|
u.user_notifications.create(message: 'Hello dear')
end
如果您有60条记录, .find_in_batches
可能并不重要,但是如果您有60,000条,则服务器将耗尽内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.