Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple has_many through associations from an array of IDs

I have models User, Photo and Favorite, where favorites is a join table from users to photos, i.e.:

class User < ActiveRecord::Base
  has_many :favorites
  has_many :photos, through: `favorites`
end

class Photo < ActiveRecord::Base
  has_many :favorites
  has_many :users, through: `favorites`
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :photo
end

Say that @user is an instance of User and photo_ids is an array of primary keys of Photos. What's the fastest and/or most succinct way to add all of those photos to @user.photos?

The best I can up with is:

@user.favorites.create( photo_ids.map { |id| {photo_id: id } } )

But this seems pretty verbose to me. Does Rails not have a better way of handling this?

Other questions talk about creating multiple has_many: through: associations through a nested form but I'm trying to do this in a JSON API so there are no forms involved.

like image 306
GMA Avatar asked Jan 16 '14 09:01

GMA


1 Answers

How about

@user.photos << Photo.find_all_by_id(photo_ids)
like image 190
BroiSatse Avatar answered Sep 20 '22 02:09

BroiSatse