2014-07-18 159 views
1

鑑於以下型號和協會:Rails:在has_many上創建/銷燬關係:通過has_and_belongs_to_many關係?

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 

與以下控制器

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 

我如何可以將照片添加到用戶的相冊?

要將照片添加到用戶的相冊,用戶可以使用包含Album.id和Photo.id的專輯照片對象向專輯照片控制器發出POST請求。這是正確的方法嗎?此外,應該進行檢查以確保current_user實際上擁有POST請求指定的Album.id。

我正在尋找適當的Rails方式來添加/刪除用戶相冊中的照片。我的人際關係&控制器可能不正確。

+0

我有一種似曾相識的感覺無比... – sevenseacat

回答

2

您可以創建自己的服務,但我寫在控制器的所有代碼:

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