2013-11-25 97 views
0

我有公司,每個公司都有很多類別 我想跟蹤每個公司的類別數量,列表樣式,並增加/減少添加/刪除,而按位置列排序。因此,公司內的每個類別都有一個Position屬性。Rails中同一模型的不同值

|pos| name 
    1 - cat1 
    2 - cat2 
    3 - cat3 

所以,當我創建一個公司,我已經有2個默認類別(之前創建,等等),並在我的類別I類有:

@@total_positions = 2 

有關分類操作位置創建我使用:

before_create :add_position_to_new 
    before_destroy :decrement_positions 

def add_position_to_new 
    self.position = @@total_positions + 1 
    @@total_positions = self.position 
end 

def decrement_positions 
    @@total_positions = @@total_positions - 1 
end 

這一切工作正常,但我在應用程序中的所有類別都有一個共同的位置計數器。我希望每個公司都有自己的@@ total_position計數器,用於他們的類別。請將我指向正確的方向。

PS:在我使用acts_as_list gem之前,它工作得很好,但後來我在切換到Postgres時遇到了一些困難,並決定從頭編寫我自己的方法。這樣你也學到更多,對吧? ;)

回答

1

如果我正確理解您的問題,您可以通過多對多關係跟蹤類別和/或公司的數量。

考慮以下幾點:

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :companies 
end 

class Company < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
end 

然後你可以在任何關聯使用size(即企業和類別),以確定相關對象的數量,像這樣:

company = # a company ... 
# returns the number of categories for the company 
company.categories.size 

category = # a category ... 
# returns the number of companies for the category 
category.companies.size 

這是不是在你的情況下工作?

+0

真棒,謝謝! –

0

聽起來你正在尋找一個counter cache

http://railscasts.com/episodes/23-counter-cache-column

更在http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference

本質部分4.1.2.3讀,一個counter cache跟蹤兒童的數量是存在一個關聯。每次創建或刪除緩存時都會更改以反映該緩存。

+0

謝謝你指點我正確的方向!快速的問題 - 這個專欄是否存儲每個單獨項目的位置編號(1,2,3,4,n)還是存儲這些項目的總量?問題是我需要根據他們的位置屬性 –

+0

對我的類別進行排序啊,這在你的問題中並不明確。事實上,我仍然不完全清楚你的意思......?嘗試更新您的問題以使該要求更清晰。 – Matt

0

說,你有屬性的模型CompanyCategories:

ID,COM​​PANY_ID,CATEGORY_ID

你可以使用,而不必單獨的位置列以增加順序的ID屬性。這將工作,除非你想要一個功能重新排序他們的類別。

相關問題