這是我的使用案例: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
關聯關係,如果有的話,爲什麼以及如何最好地做到這一點。
還在這裏學習繩索,所以如果這是一個新手/愚蠢的問題,請道歉。提前謝謝了!
有趣 - 謝謝!因此,在這種情況下,考慮到我沒有直接控制sales_tax_rate源數據來強制實現唯一性或完整性,所以在這種情況下,簡單的查找方法實際上是一種更直接的方法。並感謝您的無核查提示 - 這很好。 – nlh