根据rails

时间:2015-11-28 18:49:22

标签: ruby-on-rails activerecord

我想根据评估表更新最终得分表。你能告诉我下面代码有什么问题吗?你最后如何将数据保存在第二个表中?

Evaluation.rb

class Evaluation < ActiveRecord::Base
  belongs_to :developer
  belongs_to :supervisor
  after_save :eval_score_calculator

  def eval_score_calculator
    finalscore.score_calculator
  end
end

Final_score.rb

class FinalScore < ActiveRecord::Base
  belongs_to :developer

  def score_calculator
    @job_performance_avg = (:job_knowledge_score.to_s.to_f + :quality_score.to_s.to_f + :quantity_score.to_s.to_f)/3
    @interpersonal_skills_avg = (:team_contribution_score.to_s.to_f + :seeks_to_improve_score.to_s.to_f + :accepts_responsibility_score.to_s.to_f + :interaction_with_others_score.to_s.to_f+ :integrity_and_trust_score.to_s.to_f)/5
    @organization_skills_avg = (:organization_planning_score.to_s.to_f + :use_of_company_resources_score.to_s.to_f + :time_management_score.to_s.to_f )/3
    @final_score  = 0.5 * @job_performance_avg + 0.25 * @interpersonal_skills_avg + 0.25 * @organization_skills_avg
  end
end

1 个答案:

答案 0 :(得分:0)

1)如果要更新表,则需要.save才能将更改存储在数据库中。 因此,在获得所有计算后,您应该修改所需的列,然后保存它。 (假设final_rating是Finalscore表的一列)

class FinalScore < ActiveRecord::Base
  #other belongs_to
  belongs_to :evaluation

  def score_calculator(param1, param2)
    #your calculations...

    #update the fields you want of this final score
    self.onething = param1
    self.anotherthing = param2

    #and at the end save it
    self.save
  end
end

2)在评估课中,您应首先检索与此评估相关联的最终得分对象,然后调用score_calculator。 (假设您将此评估关联的finalscore对象的id作为评估表中的列,并且Finalscore作为表的名称)

class Evaluation < ActiveRecord::Base
   #belongs_to ...
   after_save :eval_score_calculator
   has_one :finalscore

  def eval_score_calculator

    #finds the finalscore object in the table of finalscores
    Finalscore.find(finalscore_id).score_calculator(a ,b)

  end

end

ab是您传递给evaluation的{​​{1}}对象中的字段,用于计算评估的分数,然后将其保存到{{1}表。您已更新此score_calculator个对象,并且还与我在下方建议的字段finalscore的{​​{1}}相关联。

如果您的finalscore表中没有evaluation,我建议您使用迁移添加它以简化使用并遵守与finalscore_idfinalscore_id声明的关系{1}}为此您可以查看 http://guides.rubyonrails.org/association_basics.html#the-has-one-association

3)您对所声明的每个变量使用evaluation,我只是想知道为什么。 has_one用于在控制器和视图之间传递数据。要在模型中定义变量,您只需输入belongs_to即可,无论如何,这些变量都无法在您的视图中访问。