Rails:在has_many上创建/破坏关系:通过has_and_belongs_to_many关系?

时间:2014-07-18 08:10:12

标签: ruby-on-rails

鉴于以下模型和协会:

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的AlbumsPhotos对象向AlbumsPhotosController发出POST请求。这是正确的方法吗?此外,应进行检查以确保current_user实际上具有POST请求指定的Album.id。

我正在寻找适当的Rails方式来添加/删除用户相册中的照片。我的人际关系控制器可能不正确。

1 个答案:

答案 0 :(得分: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
相关问题