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 に答える