[英]Rails: Creating/destroying relationships on has_many :through a has_and_belongs_to_many relationship?
給定以下模型和關聯:
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
如何將照片添加到用戶相冊?
要將照片添加到用戶的相冊,用戶可以使用包含Albums.id和Photo.id的AlbumsPhotos對象向AlbumsPhotosController發出POST請求。 這是正確的方法嗎? 另外,應進行檢查以確保current_user實際上具有POST請求指定的Album.id。
我正在尋找正確的Rails方式來添加/刪除用戶相冊中的照片。 我的關系和控制者可能不正確。
您可以創建自己的服務,但是我在控制器中編寫了所有代碼:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.