How Do I Store A Calculated Value In Rails -


i working on project want show post has least feedback (the goal encourage feedback on works in progress). have figured out calculation - although feedback welcome - however, having trouble assigning value column (:feedback_score) on post model. need help.

post.rb:

class post < activerecord::base     def feedback_score_calc         time_passed = ((time.now - self.created_at)/1.hour).round(3)         feedback = self.comments.count         self.feedback_score = time_passed / feedback     end end 

i need know how call method whenever new comment added, , need able calculate on form of schedule. goal display least engaged on first visit paging progress 2nd least engaged, 3rd, etc...

my other problem can't method run through console, no method error, when using def self.feedback_score_calc.

with code you've provided it, it's instance method on post. should able like

@post = post.find(some_id_here) @post.feedback_score_calc 

creating class method definition def self.feedback_score_calc isn't want do, because you're making calculations on specific instance of post , it's relations.

as @kien thanh mentioned in comments, you'll need call save on post instance after set column value if want see reflected in database.

@post = post.find(some_id_here) @post.feedback_score_calc @post.save 

or in method itself

def feedback_score_calc     time_passed = ((time.now - self.created_at)/1.hour).round(3)     feedback = self.comments.count     self.feedback_score = time_passed / feedback     save end 

also worth mentioning, can write column directly (bypassing feedback_score= method activerecord sets up) calling write_attribute this

def feedback_score_calc     time_passed = ((time.now - self.created_at)/1.hour).round(3)     feedback = self.comments.count      write_attribute(:feedback_score, time_passed / feedback)     save end 

finally, need either kill , restart console or run reload! within console when making changes model you're trying verify within console.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -