Not exactly sure how to look this up, but I’m not finding the solution anywhere. I want to assign an array of users an array of websites. Like so:
users = User.all
sites = Site.all
users.each do |user|
sites.each do |site|
user.websites << site
end
end
Obviously, this does not work because I’m missing something about block scope. However, this works:
users.each do |user|
Site.all.each do |site|
user.websites << site
end
end
But I’m trying to eliminate the extra calls to the DB (Site.all.each …) and learn something about Ruby in the process. Any help is greatly appreciated.
If your User model is in a has many relationship with Websites (classname Sites), then you can just do
Edit: For Harpastum:
If user.websites contains items not in Site.all that you don’t want over written the following works.