tommyd456
tommyd456

Reputation: 10673

Rails 4 - Building Multiple Relationships

When a user creates a new booking record, part of the data entered is an email address. This email address is used to create a new guest record at the same time if they don't already exist. The booking should have the guest id as part of the record.

In my models I have defined the relationships so:

accommodations has_many bookings
guests has_many bookings
bookings belongs_to accommodations
bookings belongs_to guests

This is what I have so far in the create action of my BookingsController:

...
def create
  accommodation = current_user.accommodation    
  @booking = accommodation.bookings.build(post_params)
  @guest = accommodation.guests.build(params[:email])

  if @booking.save  
    flash[:success] = 'The booking has been added successfully.'  
    redirect_to :controller => 'bookings', :action => 'index'
  else
    render 'new'
  end
end
...

My questions are:

Upvotes: 0

Views: 752

Answers (1)

Marcelo De Polli
Marcelo De Polli

Reputation: 29281

If you're not using @guest in the view, there's no need for it to be an instance variable. So:

accommodation = current_user.accommodation
guest = Guest.find_or_create_by(:email => params[:email])
@booking = accommodation.bookings.new(post_params.merge(:guest_id => guest.id))

You don't need to use build in your #create method because its main use is to maintain association ties with objects that still don't have a primary key. But since you're persisting your stuff in here, we can go with good old new from Ruby.

Upvotes: 1

Related Questions