Forum: Ruby on Rails Many to many questions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community 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
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.
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
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
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
for
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
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.
This topic is locked and can not be replied to.