我有四种模式:Shop
,Item
,Category
,SubCategory
Shops
与has_and_belongs_to_many
和Category
SubCategory
有关联。
Shops
与has_many
有Items
个关联。
Category
与has_many
有SubCategories
个关联。
Category
和SubCategory
has_many Items
。
当我创建Shop
时,我可以选择很多类别和子类别。
当我尝试创建Item
时,rails_admin
会为“类别”和“子类别”创建选择框。但是,有问题。 这使我可以从所有类别和子类别中进行选择。
我希望只能选择属于我所选商店的类别和子类别。
在rails_admin中是否可以根据其他模型关联更改选择枚举值?
Category
的代码
class Category
include Mongoid::Document
has_many :sub_categories, inverse_of: :category
has_many :items
accepts_nested_attributes_for :sub_categories
end
SubCategory
的代码
class SubCategory
include Mongoid::Document
has_many :items
belongs_to :category, inverse_of: :sub_categories
end
Shop
的代码
class Shop
include Mongoid::Document
has_many :items, dependent: :destroy, inverse_of: :shop
has_and_belongs_to_many :categories, inverse_of: nil
has_and_belongs_to_many :sub_categories, inverse_of: nil
accepts_nested_attributes_for :items
end
Item
的代码
class Item
include Mongoid::Document
belongs_to :shop, inverse_of: :items
belongs_to :category
belongs_to :sub_category
end
============================可能的解决方案============== =========
由于has_and_belongs_to_many
和Shop
之间存在单边Category
关联,这意味着Shop
会存储Categories
的ID数组。
我的模型也是 Mongoid Documents ,这意味着我无法使用连接。
在我的Item edit
操作中,我添加了以下代码:
field :category do
associated_collection_cache_all false
associated_collection_scope do
item = bindings[:object]
shop = item.shop
Proc.new { |scope|
scope = scope.where(id: {"$in" => shop.category_ids.map(&:to_s)}) if item.present?
}
end
end
现在它允许我按商店类别选择类别。但是,我无法在create
操作
答案 0 :(得分:2)
rails_admin支持作用域关联。参见:
https://github.com/sferik/rails_admin/wiki/Associations-scoping
例如:
config.model Item do
field :category do
associated_collection_cache_all false
associated_collection_scope do
item = bindings[:object]
Proc.new { |scope|
scope = scope.joins(:shops).where(shops: {id: item.shop_id}) if item.present?
}
end
end
end
请注意“绑定[:object]对于新父记录可以为null的警告!”。在范围生效之前,您可能必须保存项目。在过去,我已经为active_admin表单添加了一个条件,因此只有在保存记录后才会显示范围字段。