0

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:

  • Should I use 'build' twice as I want the new booking to have the guest id?
  • How can I check if guest exists already using email?
  • Is it safe/secure to use params[:email] when building the guest?
4

1 回答 1

1

如果您不在@guest视图中使用,则无需将其作为实例变量。所以:

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

您不需要build在您的#create方法中使用,因为它的主要用途是保持与仍然没有主键的对象的关联关系。但是既然你在这里坚持你的东西,我们可以new从 Ruby 开始。

于 2013-09-07T19:24:09.477 回答