1
我想在運行時擴展一個對象(ActiveRecord :: Base的實例)並調用一個類方法(添加一個has_many
關聯)。我理想中的代碼想如下:在運行時擴展對象時如何調用類方法?
class User < ActiveRecord::Base
end
module Seller
has_many :bookings, :foreign_key => :seller_id
end
module Buyer
has_many :bookings, :foreign_key => :buyer_id
end
user = User.find(1)
user.extend Seller
user.bookings
請注意,我不希望包括到User
類的模塊,我想延長單個用戶對象,而不是所有的用戶對象的行爲。