user3477405
user3477405

Reputation: 23

Rails: Creating/destroying relationships on has_many :through a has_and_belongs_to_many relationship?

Given the following models and associations:

User
    has_many :photos, through: :albums
    has_many :albums

Album
    has_and_belongs_to_many :photos
    belongs_to :user

AlbumsPhoto
    belongs_to :album
    belongs_to :photo

Photo
    has_and_belongs_to_many :albums
    has_many :user, through: :albums

And the following controllers

UsersController
    - Performs CRUD actions for Users

AlbumsController
    - Performs CRUD actions for Albums

AlbumsPhotosController * (uncertain on approach for this controller)
    - Creates/destroys an AlbumsPhoto object based on Album.id and Photo.id.
    - Effectively adds a photo to a user's album.

PhotosController
    - Performs CRUD actions for Photos

How can I add a Photo to a User's Album?

To add a Photo to a User's Album, a user can make a POST request to the AlbumsPhotosController with an AlbumsPhotos object that contains Album.id and Photo.id. Is this the correct approach? Also, a check should be made to ensure that the current_user actually has the Album.id specified by the POST request.

I am looking for the proper Rails way to add/delete Photos from a User's Album. My relationships & controllers may be incorrect.

Upvotes: 1

Views: 204

Answers (1)

uselesssmile
uselesssmile

Reputation: 124

You can create your own service, but i write all code in the controller:

class AlbumsPhotosController < ApplicationController
  def create
    album.photos << photo
  end

  private

  def photo
    photo = current_user.photos.where(name: params[:photo_name].first
    head :not_found unless photo.present?
    photo
  end

  def album
    album = current_user.albums.where(name: params[:album_name].first
    head :not_found unless album.present?
    album
  end
end

Upvotes: 2

Related Questions