Search code examples
ruby-on-railsrubyactiverecordassociationshas-many-through

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.


Solution

  • How about

    @user.photos << Photo.find_all_by_id(photo_ids)