2015-09-30 34 views
2

的枚舉場的變化值我有四個型號:ShopItemCategorySubCategoryRails_admin,根據協會

ShopsCategorySubCategoryhas_and_belongs_to_many關聯。

Shopshas_manyItems的關聯。

Categoryhas_manySubCategories的關聯。

Both Category and SubCategory has_many Items

當我創建Shop我可以選擇很多Categories和SubCategories。

當我嘗試創建Item時,rails_admin爲Categories和SubCategories創建了選擇框。但是,有問題。 它使我可以從所有類別和子類別中進行選擇。

我想只能選擇屬於我選擇的商店的類別和子類別。

是否有可能在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 

============================可能的解決方案============== =========

因爲有一個片面ShopCategory之間has_and_belongs_to_many ASSOCATION,這意味着Categories的id的Shop存儲陣列。

我的模型也是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動作

回答

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 

注意的警告, 「綁定![:對象]可以爲空對新父記錄」。您可能必須在範圍生效之前保存該項目。在過去,我爲active_admin表單添加了一個條件,所以一旦記錄被保存,範圍字段只會顯示出來。

+0

您可以將代碼中的'Item','Shop'和'Category'關聯添加到您的問題中嗎?商品是否有與商店類別分開的類別? – thebenedict

+0

編輯我的答案,但(對此抱歉),我的加入語法可能不正確,我不能輕易測試它。更正歡迎,希望這給你的想法。 – thebenedict

+1

我已編輯我的問題與可能的解決方案。 –