【发布时间】:2016-04-01 13:27:37
【问题描述】:
我为 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
我无法将我的Product-class 的class_name 引入CartItem-class。
它应该会自动添加到MongoidCart::CartItemclass 的关系。
当我“硬编码”为: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
【问题讨论】:
标签: ruby-on-rails ruby mongoid activesupport activesupport-concern