Reputation: 64
I'm trying to setup a photo gallery for each user. How would I set up the associations?
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
i have the gallery and photo model currently working. You are able to create a gallery and add photos to it. I'm confused is to how to add it to the current user?
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
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
Upvotes: 0
Views: 369
Reputation: 571
Once you grab the current user, just concatenate the gallery to the user's galleries.
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
Upvotes: 1