Rails_admin,根据关联更改枚举字段的值

时间:2015-09-30 11:22:55

标签: ruby-on-rails ruby rails-admin

我有四种模式:ShopItemCategorySubCategory

Shopshas_and_belongs_to_manyCategory SubCategory有关联。

Shopshas_manyItems个关联。

Categoryhas_manySubCategories个关联。

CategorySubCategory 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_manyShop之间存在单边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操作

上使用此功能

1 个答案:

答案 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表单添加了一个条件,因此只有在保存记录后才会显示范围字段。