一つは、(仮定の下であなたにhas_many関係が参加モデルuser_bookmark.rbを使用しています)のようなあなたの移行におけるデータ移行を含めることでした。あなたのuser.rbで
class AddBookmarksTable < ActiveRecord::Migration
def self.up
create_table :bookmarks, :force => true do |t|
t.string :some_col
t.timestamps
end
create_table :user_bookmarks, :force => true do |t|
t.integer :bookmark_id, user_id
t.timestamps
end
# create the 5 bookmarks you want to seed as values for existing users
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
# add values to the join table for your model
User.all.each{|u| Bookmark.all.each{|b| UserBookmark.create(:user_id => u.id, :bookmark_id => b.id)}}
end
def self.down
drop_table :bookmarks
end
end
あなたは
has_many :bookmarks
を持つべきです
および他の方法(優先)はちょうど私達になり
belongs_to :user
をbookmark.rbシードデータは実際に移行に属していないので、テーブルを作成するためのマイグレーションや、lib/tasks内で作業するカスタムレイクタスクを持つことができます。その後
のlib /タスク/ add_bookmarks_to_existing_users.rake
namespace :db do
desc "Add bookmarks to existing users"
task :add_bookmarks_to_existing_users => :environment do
# create seed book marks (under impression none exist right now and associations have been set up in user and bookmark models)
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
Bookmark.create(:some_col => 'value')
User.all.each{|u| u.bookmarks << Bookmark.all}
end
end
あなただけ実行することができます。
rake db:add_bookmarks_to_existing_users
ありがとう、それはかなりうまくいった! –