我为 rails 编写了一个 gem,以拥有一个小型的 mongoid 购物车。
在它得到的模型中,包括include MongoidCart::ActsAsProduct
class MyProduct
include Mongoid::Document
include MongoidCart::ActsAsProduct
end
module MongoidCart
class CartItem
include Mongoid::Document
belongs_to :mongoid_cart_cart, :class_name => 'MongoidCart::Cart'
end
end
module MongoidCart
class Cart
include Mongoid::Document
field :user_id, type: String
has_many :cart_items, :inverse_of => :cart, :class_name => 'MongoidCart::CartItem'
belongs_to :customer, :inverse_of => :carts, :class_name => MongoidCart.configuration.customer_model_name
end
end
class_name
我很难将我Product
的班级带入CartItem
班级。它应该会自动向MongoidCart::CartItem
类添加关系。当我像我一样“硬编码”时:my_product
,没有错误。
我怎样才能使:the_class_to_point_to_as_symbol
动态?
module MongoidCart
module ActsAsProduct
extend ActiveSupport::Concern
included do
#adds dynamic association to the CartItem to refer to the ActsAsProduct class
MongoidCart::CartItem.class_eval(
'belongs_to :the_class_to_point_to_as_symbol, :class_name => "Product", inverse_of: :cart_item'
)
end
end
end