Reputation: 11108
I would like to add a row to photo_albums
table in my db containing the user ID for current_user
and an album title "Posts Album" before_create
.
I achieve something similar using before_create :build_profile
to build an empty row for users personal information in my profiles table. This code is inside my user model.
I'd like to achieve something similar but in my photo_albums
table. On creation of user create an album in the photo_albums
table that will store all micropost related images. On creation of user I just need a row with album title = "post album"
and their user id.
class User < ActiveRecord::Base
has_one :profile, :autosave => true
has_many :photo_albums
has_many :microposts
before_create :build_profile
create
actiondef create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
login @user
UserMailer.join_confirmation(@user).deliver
format.js { render :js => "window.location = '#{root_path}'" }
else
format.js { render :form_errors }
end
end
end
How can I do this? Please notice a user has many photo albums so I can't use build_photo_album
. I've read some info in the guides but still can't figure this out. Would appreciate a solution.
Upvotes: 0
Views: 107
Reputation: 15791
I have no better solution then create a custom callback like this:
UPDATED (you even don't need to define user_id => self.id
in PhotoAlbum.create
params, it would be set automatically)
after_create :build_default_photo_album
def build_default_photo_album
self.photo_albums << PhotoAlbum.create(:title => "post album")
end
Upvotes: 2