Many to many questions


#1

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
hotel.id as the booking and the collection itself, since a booking is
made
on a single hotel, not many. ¿How can i accomplish that? It should be
something like :conditions => “hotel_id = self.hotel.id” (of course,
this
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
is
empty, and assign the hotel_id of the room beign added to the collection
to
the booking.hotel.

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

Please, could you give me some advices?

Thanks,
Rodrigo.


#2

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

the
instantiated booking object

note the use of single quotes around the sql fragement, this is

required
if using #{attr} in the condition
has_and_belongs_to_many :rooms, :conditions => ‘hotel_id =
#{hotel_id}’
end


#3

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
for
a collection?

Thanks again.


#4

On 12/2/05, Chris H. removed_email_address@domain.invalid wrote:

end

is this documented anywhere? (the use of attributes in :conditions)


#5

I’ve seen it used in the associations documentation examples, but there
is
nothing that i have found that actually describes usage. this is not to
say
that it isn’t documented, i just haven’t seen it.