0

Models:

class Booking < ActiveRecord::Base
    has_and_belongs_to_many :spaces
end

class Space < ActiveRecord::Base
    has_and_belongs_to_many :bookings
end

I've used habtm many as I don't need any other information, just a relationship. The idea is to add spaces to a booking object, but I'm having trouble getting the @space or array of @spaces into the booking create action. THe below code works fine and grabs all spaces from the database and adds the relationship. Obviously though, I don't want them all, I just need the instances (either @space or @spaces depending on where the user is).

def create
    @booking = Booking.new(booking_params)
    @booking.spaces = Space.all
    @booking.user_id = current_or_guest_user.id
    @booking.save
    respond_with(@booking)
end

Do I need to do this through the controller or form? I'd rather do it through the controller with something like this, which would allow me to update the relationship and add more @spaces to the array at any point.

@booking.spaces << @space
and
@booking.spaces << @spaces

However, those variables aren't available in the bookings create action. The bookings are created from the Spaces show action, which is where the form is.

Any ideas? It's possible that I'm doing something stupid in the first place...

Ralph King
  • 994
  • 1
  • 9
  • 19
  • have you created another table as `bookings_spaces` with `space_id` and `booking_id` – Sonalkumar sute Mar 04 '15 at 13:47
  • I have indeed, sorry I thought that was taken for granted. It's all working fine, I just need to know the best way to actually add to the relationship – Ralph King Mar 04 '15 at 13:50
  • If you're creating a Booking, it makes sense to present the user with the available Space options in the _form used to create the Booking. If you have a large number of Spaces for selection, then the biggest challenge is how do you effectively present the Space options for the Booking. – railsdog Mar 04 '15 at 14:19
  • They've already chosen the space, by being on the space show page - somehow I just need to pass that into the controller, they don't need to select anything – Ralph King Mar 04 '15 at 14:34

0 Answers0