2014-07-18 248 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