我正在尝试为每个用户设置照片库。我该如何设置关联?
class User < ActiveRecord::Base
has_many :photos
has_many :galleries, through :photos
end
class Gallery < ActiveRecord::Base
has_many :photos
belongs_to :user
end
class Photo < ActiveRecord::Base
belongs_to :gallery
belongs_to :user
end
我的画廊和照片模型目前正在运作。您可以创建一个库并添加照片。我很困惑如何将它添加到当前用户?
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
end
def show
@gallery = Gallery.find(params[:id])
end
def new
@gallery = Gallery.new
end
def create
@gallery = Gallery.new(params[:gallery])
if @gallery.save
flash[:notice] = "Successfully created gallery."
redirect_to @gallery
else
render :action => 'new'
end
end
def edit
@gallery = Gallery.find(params[:id])
end
def update
@gallery = Gallery.find(params[:id])
if @gallery.update_attributes(params[:gallery])
flash[:notice] = "Successfully updated gallery."
redirect_to gallery_url
else
render :action => 'edit'
end
end
def destroy
@gallery = Gallery.find(params[:id])
@gallery.destroy
flash[:notice] = "Successfully destroyed gallery."
redirect_to galleries_url
end
端
PhotosController
class PhotosController < ApplicationController
def new
@photo = Photo.new(:gallery_id => params[:gallery_id])
end
def create
@photo = Photo.new(params[:photo])
if @photo.save
flash[:notice] = "Successfully created Photo."
redirect_to @photo.gallery
else
render :action => 'new'
end
end
def edit
@photo = Photo.find(params[:id])
end
def update
@photo = Photo.find(params[:id])
if @photo.update_attributes(params[:photo])
flash[:notice] = "Successfully updated Photo."
redirect_to @Photo.gallery
else
render :action => 'edit'
end
end
def destroy
@photo = Photo.find(params[:id])
@photo.destroy
flash[:notice] = "Successfully destroyed Photo."
redirect_to @photo.gallery
end
end
答案 0 :(得分:1)
抓住当前用户后,只需将图库连接到用户的图库。
def update
@gallery = Gallery.find(params[:id])
@user = current_user
if @gallery.update_attributes(params[:gallery])
@user.galleries << @gallery
flash[:notice] = "Successfully updated gallery."
redirect_to gallery_url
else
render :action => 'edit'
end
end