0

I'm building a custom profile completeness tool in Rails 3.1. Using active_admin, the administrator wants to be able to pick model attributes and assign a score value to them. I create a table with 'name' and 'score' in it. The name being the column name to apply the score to.

I need to compare the values from the name column in the scoring table when the model gets updated. Psuedocode:

ProfileScore.find(:all, :select => "name,score").inject { |p,score|
  #this is where im stuck, 'self' == updated model hash
  p[:name] == self.attribute.updated
  score += p[:score]
}

Of course other approaches are welcome! I looked at completeness-fu but it is way out of date.

Todd Baur
  • 995
  • 8
  • 22
  • For clarification: what exactly do you want this function to return? A hash mapping `name`s to `score`s? Or one number representing the overall score? Your pseudocode's `inject` doesn't take an argument. – pje Oct 02 '12 at 22:13
  • I was looking at inject because I want it to return the total score from the score values that match the updated columns. – Todd Baur Oct 02 '12 at 22:19

2 Answers2

1
score = ProfileScore.select("name, score").inject(0) { |memo, pscore|
  # the result is a list of ProfileScore objects, not of pairs.

  # if p[:name] == self.attribute.updated # don't you want to take into account
  # also old, but present, attributes??
  if self.attributes[p[:name]].present?
    memo += p[:score]
  end
  memo
}

or also

present_attributes = self.attributes.reject { |k,v| v.blank? }.keys
score = ProfileScore.where(:name => present_attributes).sum("score")
rewritten
  • 16,280
  • 2
  • 47
  • 50
0

To get the total score, you can use:

total_score = ProfileScore.where(:name => self.attribute.updated).sum(:score)
Meier
  • 3,858
  • 1
  • 17
  • 46