在做一个简单的相册功能,三个类:user, album,photo model:
class User < ActiveRecord::Base
has_many :albums, :inverse_of => :user, :dependent => :destroy
has_many :photos, :inverse_of => :user, :dependent => :destroy
end
class Album < ActiveRecord::Base
belongs_to :user, :inverse_of => :albums, :foreign_key => 'user_id'
has_many :photos, :inverse_of => :album, :dependent => :destroy
end
class Photo < ActiveRecord::Base
belongs_to :user, :inverse_of => :photos
belongs_to :album, :inverse_of => :topics
end
routes:
resources :users, shallow: true do
resources :albums do
resources :photos
end
end
rake routes:
/albums/:album_id/photos(.:format) photos#index
/albums/:album_id/photos(.:format) photos#create
/albums/:album_id/photos/new(.:format) photos#new
/photos/:id/edit(.:format) photos#edit
/photos/:id(.:format) photos#show
/photos/:id(.:format) photos#update
/photos/:id(.:format) photos#destroy
/users/:user_id/albums(.:format) albums#index
/users/:user_id/albums(.:format) albums#create
/users/:user_id/albums/new(.:format) albums#new
/albums/:id/edit(.:format) albums#edit
/albums/:id(.:format) albums#show
/albums/:id(.:format) albums#update
/albums/:id(.:format) albums#destroy
album controller:
def index
@albums = @user.albums
end
def destroy
@user = current_user
@album = @user.albums.find(params[:id])
@album.destroy
redirect_to user_albums_path(@user)
end
我的问题:
请教正确的 destroy 应该怎么写?因为在 routes 里 albums#destroy 的路由是没有 user 的 id。
用不了@user = User.find(params[:id])
这个时候应该怎样准确的删除该用户的 album 呢?
另外,到时候如果再加多 photo_comments,routes 不就会又嵌套多一层?可是看 Guides 介绍的是不推荐超过两层的,求最佳实践?
感谢:)