hi, i'm a newbie working on my first commerical rails project. i've got some models that i'm stuck with, not sure whether i need to redesign the schema's or stick to my earlier design as i can quite get what i want from the way i've implemented my associations. Basically i want to access the bookings for a room. the room has_many beds, bed has_many booking_items and a booking_item belongs_to a booking. So how can i get the bookings for a bed??? I know i can do a find_by_sql but then i cant use :include and to be honest this seems simple enough and i'd rather stick to the rails way so to speak and use the association proxies etc. Additionally i want to get the rooms for a booking, but i think that is the same problem. I had looked at the nested has many plugin but i managed not to get that working (below). Any help would be really appreciated as i think i'm going to add a Room_Id field to the bookingItem which would mean i could use the standard rails associations. rails version: 2.1.1 schema: "beds" integer "room_id" integer "bed_number" "booking_items" integer "booking_id" integer "bed_id" integer "price" date "booking_date" "bookings" integer "user_id" integer "amount" "rooms" integer "bed_quantity" integer "floor" string "room_name" models: class Bed < ActiveRecord::Base belongs_to :room has_many :booking_items end class BookingItem < ActiveRecord::Base belongs_to :booking belongs_to :user belongs_to :bed end class Booking < ActiveRecord::Base has_many :booking_items, :dependent => :destroy has_many :payments has_many :beds, :through => :booking_items has_many :rooms, :through => :beds # THIS IS NOT WORKING end class Room < ActiveRecord::Base has_many :beds has_many :booking_items, :through => :beds has_many :bookings, :through => :booking_items, :source => :booking_items # THIS IS NOT WORKING, I TRIED TO USE NESTED HAS MANY HERE. end
on 2009-01-09 13:42
on 2009-01-09 14:01
in your Bed-model add has many :bookings, :through => :booking_items then you should be able to call bookings_for_bed_1 = Bed.find(1).bookings
on 2009-01-09 19:47
Hi, I added that and could get the bookings for a bed. but i wanted to get the bookings for a room using an association like: room.bookings i tried adding this using the nested has many plugin: has_many :bookings, :through => :booking_items to Room. but i got this error message. Mysql::Error: Unknown column 'booking_items.roomActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'booking_items.room_id' in 'where clause': SELECT `bookings`.* FROM `bookings` INNER JOIN booking_items ON bookings.id = booking_items.booking_id WHERE ((`booking_items`.room_id = 1)) Am i better off just adding Room_Id to the BookingItem model and effectively denormalising it?? Thanks for the help.