Forum: Ruby on Rails Many to many questions

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
papipo (Guest)
on 2005-12-02 15:54
(Received via mailing list)
Hello Railers!

I have 3 models: Hotel, Room and Booking

Hotel has_many :rooms, and has_many :bookings
Room belongs_to :hotel, and habtm :bookings
Booking belongs_to :hotel, and habtm :rooms

i wish to add a condition to the @booking.rooms, they should share the
same as the booking and the collection itself, since a booking is
on a single hotel, not many. ¿How can i accomplish that? It should be
something like :conditions => "hotel_id =" (of course,
doesn't work).

Another thing is that i don't know if the operator "<<" can be
redefined. If
i redefine Booking.rooms << in some way, i could check if the collection
empty, and assign the hotel_id of the room beign added to the collection
the booking.hotel.

The third thing/question/approach is that another way is to make Booking
"virtual" model, not beign saved directly until payment made, as Cart in
Agile dev with rails book.

Please, could you give me some advices?

christopher.k.hall (Guest)
on 2005-12-02 20:30
(Received via mailing list)
i think this is what you are looking for.

class Booking < ActiveRecord::Base
  belongs_to :hotel
  # this says that rooms.hotel_id has to match the hotel_id attribute of
instantiated booking object
  # note the use of single quotes around the sql fragement, this is
if using #{attr} in the condition
  has_and_belongs_to_many :rooms, :conditions => 'hotel_id =
papipo (Guest)
on 2005-12-02 22:17
(Received via mailing list)
On 12/2/05, Chris H. <removed_email_address@domain.invalid> wrote:
> end
That looks really good! i'll give it a try, thanks a lot.
Apart from that, is really possible yo redefine the "<<" method/operator
a collection?

Thanks again.
papipo (Guest)
on 2005-12-02 22:37
(Received via mailing list)
On 12/2/05, Chris H. <removed_email_address@domain.invalid> wrote:
> end
is this documented anywhere? (the use of attributes in :conditions)
christopher.k.hall (Guest)
on 2005-12-07 04:32
(Received via mailing list)
I've seen it used in the associations documentation examples, but there
nothing that i have found that actually describes usage. this is not to
that it isn't documented, i just haven't seen it.
This topic is locked and can not be replied to.