简体   繁体   中英

Rails: trying to create a has_many relationship from two tables to one table

I have two models with associated tables (villa_rooms & homes). Both have rates associated with them. I would like to use just one "rates" model with associated table to store rates for both villa_rooms and houses.

I have created the following for villa_rooms, but it is not finding associated rates:

class VillaRoom < ActiveRecord::Base
  has_many :villa_room_rates
  has_many :rates, :through => :villa_room_rates
end

class VillaRoomRates < ActiveRecord::Base
  belongs_to :villa_room
  belongs_to :rate
end

class Rate < ActiveRecord::Base
  has_one :villa_room_rate
  has_one :villa_room, :through => :villa_room_rates
end

When I try to run VillaRoom.find(1).rates I get the following error

NameError: uninitialized constant VillaRoom::VillaRoomRate

Any help is greatly appreciated.

Thanks!

I think is a spelling typo in your class VillaRoomRates, try with singular.

If you want the default behavior from Rails, all your model names should be in singular. But the tables will be created with plural names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM