Rails belongs_to_many

时间:2013-11-24 23:09:26

标签: ruby-on-rails activerecord 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

我需要的是拥有属于许多预订和租赁的汽车,而每次预订和租赁只能分配一辆汽车。

class Car < ActiveRecord::Base
    # belongs_to_many :bookings
    # belongs_to_many :rentals
end

我该怎么做?

3 个答案:

答案 0 :(得分:35)

如果汽车可以有很多预订/租赁,但预订/租赁只能有一辆车,那么您正在寻找经典的belongs_to / has_many情况。看起来你被belongs_tohas_one之间的区别绊倒了 - 它不是一个语法的,而是外键列在数据库中的位置。

  • belongs_to:“我与其中一个相关,我有外键。”
  • has_one:“我与其中一个相关,并且它有外键。”
  • has_many:“我与其中许多人有关系,他们有外键。”

请注意,has_onehas_many都暗示其他模型上有belongs_to,因为这是“此”模型具有外键的唯一选项。另请注意,这意味着has_one只应在您具有一对一关系时使用,而不是一对多关系。

考虑到这一点,我会在租赁和预订模式中将has_one :car替换为belongs_to :car,并将has_many :bookingshas_many :rentals放入您的Car模型中。同时确保您的rentalsbookings表格中包含car_id列;您的cars表格中不应包含与租借或预订相关的列。

答案 1 :(得分:2)

是的,在Rails中有一个“belongs_to_many”,有点像。这是一个更多的工作,你不能使用它的发电机。它被称为polymorphic关联。

即使你可以让一辆车有很多预订和租赁,您可以通过使其属于多变体(如rentable_vehicle)来关联汽车。您的代码看起来像这样

class Car < ActiveRecord::Base
  belongs_to :rentable_vehicle, polymorphic: true
end

class Rental < ActiveRecord::Base
  belongs_to :client, dependent: :destroy
  has_many :cars, as: :rentable_vehicle
end

class Booking < ActiveRecord::Base
  belongs_to :client, dependent: :destroy
  has_many :cars, as: :rentable_vehicle
end

答案 2 :(得分:0)

你不能做belongs_to_many。你真正得到的最接近的是has_and_belongs_to_many,但我不确定你想要的是什么 - 除非你每次出租/预订可以有多辆车。查看guide以获取完整说明。

我会改变它:

class Rental < ActiveRecord::Base
  belongs_to :client, dependent: :destroy
  belongs_to :car
end

class Booking < ActiveRecord::Base
  belongs_to :client, dependent: :destroy
  belongs_to :car
end

class Car < ActiveRecord::Base
  has_many :bookings
  has_many :rentals
end

另外,我不知道您的租金与预订有何关系,但我的直接想法是两者之间应该有一些关系,因为您可能无法预订而无需预订,对吗?