Kam*_*nek 14 activerecord ruby-on-rails associations
我是Rails的初学者,我有ActiveRecords
关联的问题.
我正在创建简单的汽车租赁服务,我做了以下协会:
class Client < ActiveRecord::Base
has_many :rentals
has_many :bookings
has_many :cars, :through => :rentals
has_many :cars, :through => :bookings
end
class Rental < ActiveRecord::Base
belongs_to :client, dependent: :destroy
has_one :car
end
class Booking < ActiveRecord::Base
belongs_to :client, dependent: :destroy
has_one :car
end
Run Code Online (Sandbox Code Playgroud)
我需要的是拥有属于许多预订和租赁的汽车,而每个预订和租赁只能分配一辆汽车.
class Car < ActiveRecord::Base
# belongs_to_many :bookings
# belongs_to_many :rentals
end
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
Dig*_*ora 36
如果一辆车可以有很多预订/租赁,但预订/租赁只能有一辆车,你会看到一个经典belongs_to
/ has_many
情况.它看起来像你被绊倒了通过区分belongs_to
和has_one
-它不是一个语法之一,但那里的外键列位于数据库的问题.
belongs_to
:"我与其中一个相关,我有外键."has_one
:"我与其中一个相关,它有外键."has_many
:"我与其中很多人有关系,他们有外键."请注意,has_one
并且has_many
两者都暗示belongs_to
在另一个模型上有一个,因为这是"this"模型具有外键的唯一选项.另请注意,has_one
只有在您具有一对一关系而非一对多关系时才应使用此方法.
考虑到这一点,我将代替has_one :car
与belongs_to :car
您的服务都和预订模型,以及地方has_many :bookings
和has_many :rentals
你的车的模型.还要确保您的rentals
和bookings
表有car_id
列; 您的cars
表格中不应包含与租赁或预订相关的列.
归档时间: |
|
查看次数: |
8297 次 |
最近记录: |