Question

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.

Was it helpful?

Solution

How about

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

OTHER TIPS

You should be able to assign to the singular_collection_ids to replace the photos.

@user.photo_ids = photo_ids

If you want to "add" to the collection, you can use |=

@user.photo_ids |= photo_ids
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top