我为铁轨编写了一个宝石,有一个小型的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
动态?# provision
config.vm.provision :shell, inline: <<-SHELL
# Set up sudo
echo 'vagrant ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/vagrant
chmod 0440 /etc/sudoers.d/vagrant
# Setup sudo to allow no-password for "sudo" commands
usermod -a -G sudo vagrant
SHELL
答案 0 :(得分:0)
我最后创建了一个生成String的新类,它由class_eval
解释并在范围之外调用它们并将字符串放在变量中:
module MongoidCart
module ActsAsProduct
extend ActiveSupport::Concern
included do
# adds dynamic association to the CartItem to refer to the ActsAsProduct class
relation_method = MongoidCart::Relation.build_product_relation_string(name)
MongoidCart::CartItem.class_eval(relation_method)
end
end
module MongoidCart
class Relation
# creates a string which can be implemented in models to provide dynamcic relation
def self.build_product_relation_string(class_name)
"belongs_to "+ ":#{class_name.to_s.underscore.to_sym}" + ", :class_name => '#{class_name.constantize}', inverse_of: :cart_item"
end
end
end
答案 1 :(得分:0)
self
块内的 included{}
是包含的类,因此您可以执行类似
included do
MongoidCart::CartItem.add_product_relation(self)
end
MongoidCart :: CartItem:
def self.add_product_relation cls
belongs_to cls.name.to_s.underscore.to_sym, class_name:cls, inverse_of: :cart_item
end