0

我正在尝试为每个用户设置一个照片库。我将如何建立协会?

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

结尾

照片控制器

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
4

1 回答 1

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
于 2012-04-07T14:19:51.720 回答