我想根据评估表更新最终分数表。您能告诉我下面的代码有什么问题吗,您如何最终将数据保存在第二个表中?
评估文件
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)如果要更新表,则需要.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
a
并且b
是从你的域evaluation
对象,你传递给score_calculator
以计算evalutaion的分数,然后将其保存到finalscore
表中。您已将此finalscore
对象更新,并且还与我在下面建议您evaluation
的字段相关联finalscore_id
。
如果你没有finalscore_id
在你的evaluation
表,我建议你使用迁移,以简化使用和遵守的关系添加它宣布has_one
和belongs_to
这个你可以看看 http://guides.rubyonrails.org/association_basics.html#有一个协会
3)您正在使用@
声明的每个变量,我只是想知道为什么。@myVar
用于在控制器和视图之间传递数据。要在模型中定义变量,只需键入不带的变量@
,无论如何这些变量在您的视图中是不可用的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句