[英]How do I use enum database values (numeric) in calculations in Rails?
在我的應用程序中,我有一個模型,該模型具有與之關聯的2個不同的枚舉參數。 我想在計算中使用這些參數(基本上是將每個參數的數據庫數字值加在一起)並返回結果。 理想情況下,我想遍歷這些模型對象,求和它們的枚舉值,並使用結果為父對象提供一個分數。
這是我的模型-用於SWOT分析:
class Swot < ActiveRecord::Base
belongs_to :sales_opportunity, inverse_of: :swots
validates :swot_details, presence: true
validates :sales_opportunity_id, presence: true
enum swot_type: [:strength, :weakness, :opportunity, :threat]
enum swot_importance: [:minimal, :marginal, :noteworthy, :significant, :critical]
before_save :update_opportunity_score
def update_opportunity_score
sales_opportunity.update_swot_score
sales_opportunity.save
end
end
我正在嘗試為update_swot_score函數編寫代碼,但是我完全不知道如何實現它。 我需要的是能夠提取所有“強度”的swot並求和swot_importance值(1表示“最小值”,2表示“ marginal” ... 5表示“ critical”),然后對“ weakness”進行相同處理的能力,在計算中使用總分之前,先說“機會”和“威脅”。
我一直在玩下面的代碼,但是現在我對自己的工作完全迷失了。 任何幫助,將不勝感激。
def update_swot_score
strength = SalesOpportunity.swots.where("swot_type <> ?", Swot.swot_types[:strength]).each do |strong|
SalesOpportunity.swots.swot_importances[strong.swot_importance]
end
end
Rails枚舉提供了一個有用的選項和整數值數組。 在Rails控制台中,運行Swot.swot_importances
並查看。 因此,您可以只從該數組中查找:
class Swot < ActiveRecord::Base
belongs_to :sales_opportunity, inverse_of: :swots
validates :swot_details, presence: true
validates :sales_opportunity_id, presence: true
enum swot_type: { strength: 1, weakness: 2, opportunity: 3, threat: 4 }
enum swot_importance: { minimal: 1, marginal: 2, noteworthy: 3,
significant: 4, critical: 5 }
before_save :update_opportunity_score
def update_opportunity_score
sales_opportunity = swot_score
end
def swot_score
Swot.swot_types[swot_type] + Swot.swot_importances[swot_importance]
end
end
請注意,無需指定self.
在模型中。 另外,您始終想使用save!
除非您要檢查返回值,否則save
可能會失敗。 但是保存在before回調中是多余的。 另外,您應該顯式指定枚舉的整數值,因為您將其用於業務邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.