运行方法后,为什么我的Rails模型属性没有更新?

时间:2015-02-05 09:35:57

标签: ruby-on-rails ruby attributes

我有一个带有两个模型的Rails应用程序 - SalesOpportunity和Swot:

SalesOpportunity:

class SalesOpportunity < ActiveRecord::Base
has_many :swots, dependent: :destroy, inverse_of: :sales_opportunity
before_save :update_swot_score


def update_swot_score
    strong = 0
    weak = 0
    opp = 0
    threat = 0

    self.swots.each do |s|
        if s.strength?
            strong = strong + Swot.swot_importances[s.swot_importance]

        elsif s.weakness?
            weak = weak + Swot.swot_importances[s.swot_importance]  

        elsif s.opportunity?
            opp = opp + Swot.swot_importances[s.swot_importance]

        elsif s.threat?
            threat = threat + Swot.swot_importances[s.swot_importance]
        end
    end

        swot_strength_score = strong - weak
        swot_opp_score = opp - threat

        puts swot_strength_score
        puts swot_opp_score

        if swot_strength_score == 0 && swot_opp_score == 0
            swot_score = 0

        elsif swot_strength_score > 0 && swot_opp_score >=0 || swot_strength_score = 0 && swot_opp_score > 0
            swot_score = 1

        elsif swot_strength_score > 0 && swot_opp_score < 0
            swot_score = 2

        elsif swot_strength_score <=0 && swot_opp_score < 0
            swot_score = 3

        elsif swot_strength_score <0 && swot_opp_score >= 0
            swot_score = 4
        end

            puts swot_score 
            return swot_score
                sales_opportunity.update_attributes!
end

旅游的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: 1, marginal: 2, noteworthy: 3, significant: 4, critical: 5 }
before_save :update_opportunity_score

def update_opportunity_score
    sales_opportunity.update_swot_score
    sales_opportunity.save
end
end

正如您所看到的,我正在向SalesOpportunities添加swots,在保存新的Swot后,我在SalesOpportunity模型中运行update_swot_score方法,该方法遍历swots并在返回swot_score之前计算一堆值。我打算使用swot_score为每个分数显示不同的消息 - 但是在完成update_swot_score方法后,我似乎无法在数据库中保存swot_score属性。

我在控制台中运行它很好(s被定义为我的SalesOpportunities之一,已经添加了swots):

irb(main):014:0> s.update_swot_score
2
1
1
=> 1

这是正确的结果 - swot_strength_score应该是2,swot_opp_score应该是1,因此swot_score也应该是1.但是当我运行时:

irb(main):015:0> s.swot_score
=> 0

如您所见,swot_score现在为零(这是它在db中的默认值)。我尝试过使用.save!,.save,.update_attributes甚至尝试在方法结束时保存sales_opportunity,但无济于事。我确信这是一个非常愚蠢的问题,有一个明显的答案,但我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

这是红宝石陷阱之一。当你这样做时:

swot_score = 0

您创建局部变量,而不是更改实例属性值。在您的情况下,swot_score等实例属性是方法,您需要执行方法swot_score=来分配它。输入:

self.swot_score = 0

它将使解析器意识到你想在当前的自我对象上执行swot_score=方法而不是创建局部变量。