2013-01-21 29 views
0

這是我的使用案例:Mongoid與預定義對象模型的關係?

我收集了一個完整的從CSV文件導入的銷售稅率的集合。我創建了Mongoid模型鏡像字段名(這是不可更改):

class SalesTaxRate 
    include Mongoid::Document 

    field :state, type: String 
    field :zip_code, type: String 
    field :tax_region_name, type: String 
    field :tax_region_code, type: String 
    field :combined_rate, type: Float 
end 

接下來,我建立一個模型,在我的應用程序使用。比方說,我想創建一種叫做地點:

class Location 
    include Mongoid::Document 

    field :name, type: String 
    field :street, type: String 
    field :city, type: String 
    field :state, type: String 
    field :zip_code, type: String 
end 

我希望能夠得到一個位置的營業稅稅率僅僅通過調用類似這樣:

home = new Location(...) 
home.sales_tax_rate 

我永遠通過home設定費率,只需查看。

什麼是「正確」的方式來做到這一點?我能想到的兩種方法 - 簡單的方法似乎只是定義確實查找的方法,像這樣:

class Location 
    ... 
    def sales_tax_rate 
    SalesTaxRate.where(zip_code: self.zip_code).first.combined_rate 
    end 

而這個工作。但我想知道我是否應該使用belongs_to關聯關係,如果有的話,爲什麼以及如何最好地做到這一點。

還在這裏學習繩索,所以如果這是一個新手/愚蠢的問題,請道歉。提前謝謝了!

回答

1

如果您有zip_code模型SalesTaxRate上的索引,您所做的與belongs_to將做的基本相同。只要有一個零檢查你的代碼,以確保它不會失敗:

SalesTaxRate.where(zip_code: self.zip_code).first.try(:combined_rate) 
# or 
rate = SalesTaxRate.where(zip_code: self.zip_code).first 
rate.nil? ? nil : rate.combined_rate 

如果你還想去belongs_to路線,你可以定義zip_code在你的SalesTaxRate身份。但是,如果你這樣做,你應該注意一些事情:首先,導入數據中的所有郵編必須是唯一的。其次,您的位置模型不能有任何在SalesTaxRate中不可用的郵政編碼,否則您將面臨問題。

+0

有趣 - 謝謝!因此,在這種情況下,考慮到我沒有直接控制sales_tax_rate源數據來強制實現唯一性或完整性,所以在這種情況下,簡單的查找方法實際上是一種更直接的方法。並感謝您的無核查提示 - 這很好。 – nlh