Rails:迁移生产数据库,需要为每个现有用户创建新数据
我的 Ruby on Rails 应用程序中有一个生产数据库,其中包含用户和其他内容。现在,在实现新功能时,我需要为每个现有用户创建一些新数据。有什么聪明的方法可以做到吗?也许是 Rake 脚本?
更多详细信息:
我有一个用户表。现在我添加了书签表。这个想法是,默认情况下每个用户都有 5 个带有预填充数据的书签。对于新用户来说很容易做到,但现有用户呢?在用户登录时创建数据是一种选择,但感觉有点脏。
谢谢!
I have a production db in my Ruby on Rails application, with users and stuff. Now when implementing a new feature I need to create some new data for every existing user. Is there some clever way to do it? Rake script maybe?
More details:
I have a User table. Now I added Bookmarks table. The idea is that every user has 5 bookmarks with prefilled data by default. Easy to do for new users, but how about existing ones? Creating the data on user login is one option, but it feels kinda dirty.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我喜欢使用
rails runner
来完成这样的一次性脚本,它允许您轻松运行加载了 Rails env 的脚本。 。如果您有很多用户,我建议使用 activerecord-import 来加快速度。
我们可以在脚本目录中创建一个名为 make_bookmarks.rb 的脚本,如下所示:
然后运行它
rails runner script/make_bookmarks.rb
I like to use
rails runner
for one off scripts like this which allows you to easily run scripts with the rails env loaded. .I suggest using activerecord-import to speed it up if you have lots of users.
We could make a script called make_bookmarks.rb in the scripts directory like this:
then to run it
rails runner scripts/make_bookmarks.rb
一种是在迁移中包含数据转换(假设您的 has_many 关系使用连接模型 user_bookmark.rb):
在您的 user.rb 中,您应该有
和 bookmark.rb
另一种方法(首选)是仅使用您的迁移来创建表,因为种子数据并不真正属于迁移,并且有一个自定义的 rake 任务可以在 lib/tasks 中为您完成工作。
lib/tasks/add_bookmarks_to_existing_users.rake
之后你可以运行:
One was to include the data transition in your migration like (under the assumption your has_many relationship uses a join model user_bookmark.rb):
In your user.rb you should have
and bookmark.rb
The other way (preferred) would be to just use your migration to create your tables, because seed data doesn't really belong in a migration, and to have a custom rake task that does the work for you inside lib/tasks.
lib/tasks/add_bookmarks_to_existing_users.rake
After that you can just run: