Opinion on saving objects needed

Hello,

Well, right now I have the following models. I have three tables:
users, events and attendances. Attendances is a join table that
contains the event_id, user_id and rsvp (boolean representing if the
user is going or not to the event). Just after creating a new event I
save the event object on the events table and continue saving the user
who created the event on the attendances table. Below I’ll show the
code that does this. I just don’t feel it is the right way to do it,
so your opinion is of great value on how it can be improved. Thanks!

class Event < ActiveRecord::Base

has_many :attendances
has_many :users, :through => :attendances

end

class User < ActiveRecord::Base

has_many :attendances
has_many :events, :through => :attendances

end

class Attendance < ActiveRecord::Base

belongs_to :event
belongs_to :user

end

def create
@event = Event.new(params[:event])
@attendance = Attendance.new(:user_id => current_user.id)
respond_to do |format|
if @event.save
@attendance.event_id = @event.id
@attendance.save
flash[:notice] = ‘Event was successfully created.’
format.html { redirect_to
invite_more_friends_neighborhood_event_path(@event.user.neighborhood,@event)
}
format.xml { render :xml => @event, :status
=> :created, :location => @event } if logged_in? && admin?
else
# Added to show again all the event_categories on the form
flash[:error] = ‘Sorry, we found some errors.’
@event_categories = EventCategory.find(:all)
@friends = current_user.mutual_friends
format.html { render :action => “new” }
format.xml { render :xml => @event.errors, :status
=> :unprocessable_entity } if logged_in? && admin?
end
end
end

Basically that look like perfect working code.

You could do it a touch more compact like:

@event = Event.new(params[:event])
if @event.save
if @event.attendances.create(:user_id => current_user.id)

Thanks for your answer Thorsten. I got into something like this too:

@event.attendances << current_user.attendances.build

What do you think about it?

Thanks for your answer Thorsten. I got into something like this too:

@event.attendances << current_user.attendances.build

What do you think about it?